次の設定でログインが要求されないのはなぜですか? /public/userにアクセスしようとすると、エラー403(アクセス拒否)が発生します。しかし、コメントした行のコメントをWebServiceSecurityConfiguration.configure
にすると、必要に応じてログインページにリダイレクトされました。 antMatcherが最初に別のパスとマッチするので、ログインが正しく構成されているために、これらの行がなぜ必要なのですか。私はAuthenticationEntryPoint
を誤って構成するいくつかの競合があると思いますが、どういうことが起こっているのか分かりません。私が達成しようとしているのは、JWTトークンを取得するためのログインパスとトークンに対して認証するWebサービスの2つのセキュリティチェーンを設定することです。コメントアウトされていない行はすべて完璧に機能しますが、私は事故によって気づきました。ログインがなくてもログインができなくなり、なぜそれほど混乱していますか?春のセキュリティJava構成の混乱
@Configuration
@Profile("javasecurity")
@Order(11)
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private TokenHandler tokenHandler;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").authorities(new SimpleGrantedAuthority("ROLE_USER")).and()
.withUser("admin").password("password").authorities(
new SimpleGrantedAuthority("ROLE_USER"),
new SimpleGrantedAuthority("ROLE_ADMIN")).and()
.withUser("guest").password("guest").authorities(new SimpleGrantedAuthority("ROLE_GUEST"));
}
@Override
@Bean
public UserDetailsService userDetailsServiceBean() throws Exception {
return super.userDetailsServiceBean();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/public/**")
.permitAll()
.and()
.formLogin()
.successHandler(authenticationSuccessHandler())
.and()
.logout();
}
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler() {
return new AuthenticationSuccessHandler() {
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
tokenHandler.setToken(response, authentication.getName());
response.getWriter().println("User authenticated and cookie sent");
response.flushBuffer();
}
};
}
@Configuration
@Profile("javasecurity")
@Order(10)
public static class WebServiceSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private TestAuthenticationFilter testAuthenticationFilter;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/secured/**")
.authenticated();
// .and()
// .antMatcher("/secured/**")
// .securityContext().securityContextRepository(new NullSecurityContextRepository())
// .and()
// .addFilterAt(testAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
}
-
@Component("TestAuthenticationFilter")
public class TestAuthenticationFilter extends GenericFilterBean {
@Autowired
private TokenHandler tokenHandler;
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
System.out.println("TestAuthenticationFilter doFitler");
attemptAuthentication((HttpServletRequest) request);
chain.doFilter(request, response);
clearAuthentication();
System.out.println("doFitler end");
}
public void attemptAuthentication(HttpServletRequest request) {
try {
UserDetails user = tokenHandler.loadUserFromToken(request);
UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(user, user.getPassword());
SecurityContextHolder.getContext().setAuthentication(auth);
} catch (Exception e) {
// Do nothing
}
}
public void clearAuthentication() {
SecurityContextHolder.getContext().setAuthentication(null);
}
@Configuration
public static class DisableFilterRegistration {
@Autowired
private TestAuthenticationFilter filter;
@Bean
public FilterRegistrationBean disablerBean() {
FilterRegistrationBean bean = new FilterRegistrationBean(filter);
bean.setEnabled(false);
return bean;
}
}
}
-
@Component("TokenHandler")
public class TokenHandler {
@Autowired(required = false)
private UserDetailsService userDetailsService;
public void setToken(HttpServletResponse response, String username) {
response.addCookie(new Cookie("user", username));
}
public UserDetails loadUserFromToken(HttpServletRequest request) throws BadCredentialsException {
Cookie[] cookies = request.getCookies();
Cookie token = null;
for (Cookie c : cookies) {
if (c.getName().equals("user")) {
token = c;
break;
}
}
if (token == null)
return null;
else
return userDetailsService.loadUserByUsername(token.getValue());
}
}
-
@RestController
@RequestMapping("/public")
public class PublicController {
@GetMapping("/norole")
public String noRole() {
return "no role";
}
@GetMapping("/user")
@PreAuthorize("hasRole('ROLE_USER')")
public String roleUser() {
return "role_user";
}
}
-
@RestController
@RequestMapping("/secured")
public class SecuredController {
@GetMapping("/user")
@PreAuthorize("hasRole('ROLE_USER')")
public String roleUser() {
return "role_user";
}
@GetMapping("/admin")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public String roleAdmin() {
return "role_admin";
}
@GetMapping("/norole")
public String noRole() {
return "no role";
}
}