내 문제는 사용자가으로 로그인 할 때 사용자를 인증 할 수 없다는 것입니다. 내가 hasRole("CUSTOMER")
를 사용하는 경우스프링 보안 + JWT + 인증 및 hasRole이 작동하지 않습니까?
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// Web Security
@Autowired
private UserDetailsService userDetailsService;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
// Authentication and Authorization
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
//h2 database console
http.headers().frameOptions().disable();
http.exceptionHandling()
.and().anonymous()
.and().servletApi()
.and().headers().cacheControl();
http.addFilterBefore(
new JWTLoginFilter("/login", authenticationManager()),
UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(
new JWTAuthenticationFilter(),
UsernamePasswordAuthenticationFilter.class);
http.authorizeRequests()
.antMatchers(HttpMethod.GET, "/api/**").authenticated()
.antMatchers(HttpMethod.GET, "/login").permitAll();
http.logout()
.logoutUrl("/api/logout")
.logoutSuccessUrl("/api/index")
.invalidateHttpSession(true);
}
}
다음 값 message: Access is denied
와 reponse 다음과 같이 나는, 내 WebSecurityConfig 파일에 문제가있는 것 같아요. 문제가있는 곳을 모르겠습니다. 여러 관련 파일 : JWTLoginFilter :
public class JWTLoginFilter extends AbstractAuthenticationProcessingFilter {
public JWTLoginFilter(String url, AuthenticationManager authManager) {
super(new AntPathRequestMatcher(url));
setAuthenticationManager(authManager);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
User credentials = new User(request.getParameter("username"), request.getParameter("email"), request.getParameter("password"));
return getAuthenticationManager().authenticate(
new UsernamePasswordAuthenticationToken(
credentials.getEmail(),
credentials.getPassword(),
Collections.emptyList()
)
);
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
TokenAuthenticationService.addAuthentication(response, authResult.getName());
}
} JWTAuthenticationFilter :
public class JWTAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
Authentication authentication = TokenAuthenticationService.getAuthentication((HttpServletRequest) servletRequest);
SecurityContextHolder.getContext().setAuthentication(authentication);
filterChain.doFilter(servletRequest, servletResponse);
}
} TokenAuthenticationService
public class TokenAuthenticationService {
static final long EXPIRATIONTIME = 864_000_000; // 10 days
static final String SECRET = "ThisIsASecret";
static final String TOKEN_PREFIX = "Bearer";
static final String HEADER_STRING = "Authorization";
public static void addAuthentication(HttpServletResponse res, String username) {
String JWT = Jwts.builder()
.setSubject(username)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATIONTIME))
.signWith(SignatureAlgorithm.HS512, SECRET)
.compact();
res.addHeader(HEADER_STRING, TOKEN_PREFIX+ " " + JWT);
}
public static Authentication getAuthentication(HttpServletRequest request) {
String token = request.getHeader(HEADER_STRING);
if (token != null) {
// parse the token.
String user = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
.getBody()
.getSubject();
return user != null ?
new UsernamePasswordAuthenticationToken(user, null, emptyList()) :
null;
}
return null;
}
} 도와주세요! 감사!
안녕하세요, 내 repo 링크입니다. https://github.com/homanhluc/spring-boot-restful-gamesaccountshop-server –
도움을 주셔서 감사합니다. 내 문제를 해결할 수 있기를 바랍니다. –