20 | Id: {currentUser.id} 21 |
22 |23 | Email: {currentUser.email} 24 |
25 | 26 | 27 | 28 | 29 |
5 |
6 | # Local setup
7 |
8 | Step 1: Download or clone the source code from GitHub to a local machine
9 |
10 | # Backend
11 |
12 | Step 2: ```mvn clean install```
13 |
14 | Step 3: ```mvn spring-boot:run```
15 |
16 | # Frontend
17 |
18 | Step 4: ```npm install or yarn install```
19 |
20 | Step 5: ```npm start or yarn start```
21 |
22 | # From the browser call the endpoint http://localhost:9080/.
23 |
24 | # User Registration
25 |
26 |
27 | # User Signin
28 |
29 |
30 | # Profile View:
31 |
32 |
33 | # Access Resource:
34 |
35 |
--------------------------------------------------------------------------------
/react-redux-jwt/src/actions/auth.js:
--------------------------------------------------------------------------------
1 | import {
2 | REGISTER_SUCCESS,
3 | REGISTER_FAIL,
4 | LOGIN_SUCCESS,
5 | LOGIN_FAIL,
6 | LOGOUT,
7 | SET_MESSAGE,
8 | } from "./types";
9 |
10 | import AuthService from "../services/auth.service";
11 |
12 | export const register = (username, email, password) => (dispatch) => {
13 | return AuthService.register(username, email, password).then(
14 | (response) => {
15 | dispatch({
16 | type: REGISTER_SUCCESS,
17 | });
18 |
19 | dispatch({
20 | type: SET_MESSAGE,
21 | payload: response.data.message,
22 | });
23 |
24 | return Promise.resolve();
25 | },
26 | (error) => {
27 | const message =
28 | (error.response &&
29 | error.response.data &&
30 | error.response.data.message) ||
31 | error.message ||
32 | error.toString();
33 |
34 | dispatch({
35 | type: REGISTER_FAIL,
36 | });
37 |
38 | dispatch({
39 | type: SET_MESSAGE,
40 | payload: message,
41 | });
42 |
43 | return Promise.reject();
44 | }
45 | );
46 | };
47 |
48 | export const login = (username, password) => (dispatch) => {
49 | return AuthService.login(username, password).then(
50 | (data) => {
51 | dispatch({
52 | type: LOGIN_SUCCESS,
53 | payload: { user: data },
54 | });
55 |
56 | return Promise.resolve();
57 | },
58 | (error) => {
59 | const message =
60 | (error.response &&
61 | error.response.data &&
62 | error.response.data.message) ||
63 | error.message ||
64 | error.toString();
65 |
66 | dispatch({
67 | type: LOGIN_FAIL,
68 | });
69 |
70 | dispatch({
71 | type: SET_MESSAGE,
72 | payload: message,
73 | });
74 |
75 | return Promise.reject();
76 | }
77 | );
78 | };
79 |
80 | export const logout = () => (dispatch) => {
81 | AuthService.logout();
82 |
83 | dispatch({
84 | type: LOGOUT,
85 | });
86 | };
87 |
--------------------------------------------------------------------------------
/spring-boot-security-jwt/src/main/java/com/knf/dev/security/jwt/JwtUtils.java:
--------------------------------------------------------------------------------
1 | package com.knf.dev.security.jwt;
2 |
3 | import java.util.Date;
4 |
5 | import org.slf4j.Logger;
6 | import org.slf4j.LoggerFactory;
7 | import org.springframework.beans.factory.annotation.Value;
8 | import org.springframework.security.core.Authentication;
9 | import org.springframework.stereotype.Component;
10 |
11 | import com.knf.dev.security.services.UserDetailsImpl;
12 |
13 | import io.jsonwebtoken.*;
14 |
15 | @Component
16 | public class JwtUtils {
17 | private static final Logger logger = LoggerFactory.getLogger(JwtUtils.class);
18 | @Value("${knf.app.jwtExpirationMs}")
19 | private int jwtExpirationMs;
20 | @Value("${knf.app.jwtSecret}")
21 | private String jwtSecret;
22 |
23 | public boolean validateJwtToken(String authToken) {
24 | try {
25 | Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
26 | return true;
27 | } catch (SignatureException e) {
28 | logger.error("Invalid JWT signature: {}", e.getMessage());
29 | } catch (MalformedJwtException e) {
30 | logger.error("Invalid JWT token: {}", e.getMessage());
31 | } catch (ExpiredJwtException e) {
32 | logger.error("JWT token is expired: {}", e.getMessage());
33 | } catch (UnsupportedJwtException e) {
34 | logger.error("JWT token is unsupported: {}", e.getMessage());
35 | } catch (IllegalArgumentException e) {
36 | logger.error("JWT claims string is empty: {}", e.getMessage());
37 | }
38 |
39 | return false;
40 | }
41 |
42 | public String generateJwtToken(Authentication authentication) {
43 |
44 | UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
45 |
46 | return Jwts.builder().setSubject((userPrincipal.getUsername())).setIssuedAt(new Date())
47 | .setExpiration(new Date((new Date()).getTime() + jwtExpirationMs))
48 | .signWith(SignatureAlgorithm.HS512, jwtSecret).compact();
49 | }
50 |
51 | public String getUserNameFromJwtToken(String token) {
52 | return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getSubject();
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/spring-boot-security-jwt/src/main/java/com/knf/dev/security/services/UserDetailsImpl.java:
--------------------------------------------------------------------------------
1 | package com.knf.dev.security.services;
2 |
3 | import java.util.Collection;
4 | import java.util.Objects;
5 |
6 | import org.springframework.security.core.GrantedAuthority;
7 | import org.springframework.security.core.userdetails.UserDetails;
8 |
9 | import com.fasterxml.jackson.annotation.JsonIgnore;
10 | import com.knf.dev.models.User;
11 |
12 | public class UserDetailsImpl implements UserDetails {
13 | private static final long serialVersionUID = 1L;
14 |
15 | private Long id;
16 |
17 | private String username;
18 |
19 | private String email;
20 |
21 | @JsonIgnore
22 | private String password;
23 |
24 | public UserDetailsImpl(Long id, String username, String email, String password) {
25 | this.id = id;
26 | this.username = username;
27 | this.email = email;
28 | this.password = password;
29 |
30 | }
31 |
32 | public static UserDetailsImpl build(User user) {
33 |
34 | return new UserDetailsImpl(user.getId(), user.getUsername(), user.getEmail(), user.getPassword());
35 | }
36 |
37 | public Long getId() {
38 | return id;
39 | }
40 |
41 | public String getEmail() {
42 | return email;
43 | }
44 |
45 | @Override
46 | public String getPassword() {
47 | return password;
48 | }
49 |
50 | @Override
51 | public String getUsername() {
52 | return username;
53 | }
54 |
55 | @Override
56 | public boolean isAccountNonExpired() {
57 | return true;
58 | }
59 |
60 | @Override
61 | public boolean isAccountNonLocked() {
62 | return true;
63 | }
64 |
65 | @Override
66 | public boolean isCredentialsNonExpired() {
67 | return true;
68 | }
69 |
70 | @Override
71 | public boolean isEnabled() {
72 | return true;
73 | }
74 |
75 | @Override
76 | public boolean equals(Object o) {
77 | if (this == o)
78 | return true;
79 | if (o == null || getClass() != o.getClass())
80 | return false;
81 | UserDetailsImpl user = (UserDetailsImpl) o;
82 | return Objects.equals(id, user.id);
83 | }
84 |
85 | @Override
86 | public Collection extends GrantedAuthority> getAuthorities() {
87 | // TODO Auto-generated method stub
88 | return null;
89 | }
90 | }
91 |
--------------------------------------------------------------------------------
/spring-boot-security-jwt/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |