Spring Boot JWT を使用してログインしようとすると、JSON 応答 (200 OK) の代わりに常に 302 応答が返されます。 Spring boot.i に Http リクエストを送信するための HttpClient は、Web 上のすべてのソリューションを試しましたが、残念ながらどれも機能していません !!!!
@EnableWebSecurity
public class SecurityTasks extends WebSecurityConfigurerAdapter{
@Autowired
private UserDetailsService userDetailsService;
@Autowired
private BCryptPasswordEncoder bcrypt;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(bcrypt);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.authorizeRequests().antMatchers("/login/**","/register/**","/").permitAll();
http.authorizeRequests().antMatchers(HttpMethod.POST,"/tasks/**").hasAuthority("ADMIN");
http.authorizeRequests().anyRequest().authenticated();
// authenticationManager() will return authentication object
http.addFilter(new JWTAuthenticationFilter(authenticationManager()));
http.addFilterBefore(new JWTAuthorizationFilter(),UsernamePasswordAuthenticationFilter.class);
}
}
JWTAuthorization コード:
public class JWTAuthorizationFilter extends OncePerRequestFilter{
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse res, FilterChain filterChain)
throws ServletException, IOException {
res.addHeader("Access-Control-Allow-Origin", "*");
res.addHeader("Access-Control-Allow-Headers",
"Origin,Accept,X-Requested-With,Content-Type,"
+ "Access-Control-Request-Method,"
+ "Acces-Control-Request-Headers,"
+ "Authorization");
res.addHeader("Access-Control-Expose-Headers",
"Access-Control-Allow-Origin,"
+ "Access-Control-Allow-Credentials,Authorization");
if(request.getMethod().equals("OPTIONS")){
res.setStatus(HttpServletResponse.SC_OK);
}
String jwt = request.getHeader(SecurityConstants.HEADER_STRING);
System.out.println("***********c*************"+jwt+"*********************");
if (jwt == null || !jwt.startsWith(SecurityConstants.TOKEN_PREFIX)) {
filterChain.doFilter(request, res); return;
}
Claims claims = Jwts.parser()
.setSigningKey(SecurityConstants.SECRET)
.parseClaimsJws(jwt.replace(SecurityConstants.TOKEN_PREFIX,""))
.getBody();
String username = claims.getSubject();
ArrayList<Map<String,String>> roles = (ArrayList<Map<String,String>>) claims.get("roles");
Collection<GrantedAuthority> authoroties = new ArrayList<>();
roles.forEach(t->{authoroties.add(new SimpleGrantedAuthority(t.get("authority")));});
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,null,authoroties);
// context security de spring this set will charge utilisateur authentifie
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
filterChain.doFilter(request, res);
}
}