The tutorial explain which use spring security create jwt protect API.
- Import dependencies:
- 1.1. pom.xml
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>
spring-boot-starter-security
</artifactId>
</dependency>
- 1.1. pom.xml
- Customize Config:
- 2.1. WebSecurityConfig.jav
a
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers(“/auth/**”).permitAll()
.anyRequest().authenticated()
.and()
.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
}antMatchers("/auth/**").permitAll()
: the address match /auth/* does’t verify it.anyRequest().authenticated()
: all request need verify authentication.exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
: add handle AuthenticationException.http.addFilterBefore
: add customize filter for request and response.
- 2.1. WebSecurityConfig.jav
- Customize Filter:
- 3.1. JwtAuthTokenFilter.jav
a
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String jwt = getJwt(request);
if (jwt != null && tokenProvider.validateJwtToken(jwt)) {
String username = tokenProvider.getUserNameFromJwtToken(jwt);
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}UsernamePasswordAuthenticationToken
: create AuthenticationToken.SecurityContextHolder.getContext().setAuthentication
: set Authentication object in SecurityContext.filterChain.doFilter
: add filter for request and response.
- 3.1. JwtAuthTokenFilter.jav
- Customize exception handler:
- 4.1 handler.java
@Component
public class JwtAuthEntryPoint implements AuthenticationEntryPoint {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthEntryPoint.class);
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {response.sendError(HttpServletResponse.SC_UNAUTHORIZED, “Error -> Unauthorized”);
}
}signUpRequest.getRole()
: get user’s roles from request
- 4.1 handler.java
- Protected API:
- controller.java:
@GetMapping(“/api/admin”)
@PreAuthorize(“hasRole(‘ADMIN’)”)
public String adminAccess() {
return “Admin Contents”;
}@PreAuthorize("hasRole('ADMIN')")
: if the user is a admin who can access contents.
- controller.java:
Reference:
Angular Spring Boot JWT Authentication example | Angular 6 + Spring Security + MySQL Full Stack
Spring Security簡介與第一個login畫面
www.SpringBootDev.com