我想用 remember-me
在我的登录中。但它不起作用,我不知道该怎么办。前端由vue.js开发,后端由spring boot开发,所以 Login
api有自定义的身份验证过滤器,可以通过json发送数据。即使“alwaysremember”设置为“true”,也不会显示cookie。
这是我的自定义身份验证过滤器。
public class CustomAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
private boolean postOnly = true;
private HashMap<String, String> jsonRequest;
@Override
protected String obtainPassword(HttpServletRequest request) {
String passwordParameter = super.getPasswordParameter();
if(request.getHeader("Content-Type").equals(ContentType.APPLICATION_JSON.getMimeType())) {
return jsonRequest.get(passwordParameter);
}
return request.getParameter(passwordParameter);
}
@Override
protected String obtainUsername(HttpServletRequest request) {
String usernameParameter = super.getUsernameParameter();
if(request.getHeader("Content-Type").equals(ContentType.APPLICATION_JSON.getMimeType())) {
return jsonRequest.get(usernameParameter);
}
return request.getParameter(usernameParameter);
}
@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response){
if(postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException("Authentication method not supported : " + request.getMethod());
}
if(request.getHeader("Content-Type").equals(ContentType.APPLICATION_JSON.getMimeType())) {
ObjectMapper objectMapper = new ObjectMapper();
try {
this.jsonRequest = (HashMap<String, String>) objectMapper.readValue(request.getReader().lines().collect(Collectors.joining()),
new TypeReference<Map<String, String>>() {
});
} catch (IOException e) {
e.printStackTrace();
throw new AuthenticationServiceException("Request Content-Type(application/json) Parsing Error");
}
}
String username = obtainUsername(request);
String password = obtainPassword(request);
//String rememberMe = request.getParameter("remember-me");
if(username == null) username = "";
if(password == null) username = "";
username = username.trim();
UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
@Override
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
}
安全配置代码如下。
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig extends WebSecurityConfigurerAdapter {
private final CustomOAuth2UserService customOAuth2UserService;
private final MemberService memberService;
private final DataSource dataSource;
private final RestAuthenticationEntryPoint restAuthenticationEntryPoint;
private final AuthFailureHandler authFailureHandler;
private final AuthSuccessHandler authSuccessHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.mvcMatchers("/","/tour", "/login", "/check-email-token", "/test", "/tour-search",
"/tour-popular", "/docs", "/your-profile", "/send-email",
"/email-login", "/check-email-login", "/login-link", "/sign-up", "/sign-up-oauth").permitAll()
.antMatchers("/valid-nickname/**", "/valid-email/**").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/tour-detail/**").permitAll()
.anyRequest().authenticated();
http.oauth2Login()
.userInfoEndpoint()
.userService(customOAuth2UserService);
http.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint); // 인증 실패시 401
http.formLogin().disable();
http.logout()
.logoutSuccessUrl("/");
// 로그인 유지
String rememberKey = "remember_me";
http.rememberMe()
.key(rememberKey)
.rememberMeParameter(rememberKey)
.rememberMeCookieName(rememberKey)
.userDetailsService(memberService)
.alwaysRemember(true)
.tokenRepository(tokenRepository());
http.csrf().disable();
http.cors();
// Json
http.addFilterBefore(customAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
// Json
@Bean
public CustomAuthenticationFilter customAuthenticationFilter() throws Exception {
CustomAuthenticationFilter filter = new CustomAuthenticationFilter();
try {
filter.setFilterProcessesUrl("/login");
filter.setAuthenticationManager(this.authenticationManagerBean());
filter.setUsernameParameter("email");
filter.setPasswordParameter("password");
filter.setAuthenticationSuccessHandler(authSuccessHandler);
//filter.setAuthenticationFailureHandler(authFailureHandler);
} catch (Exception e) {
e.printStackTrace();
}
return filter;
}
@Bean
public PersistentTokenRepository tokenRepository() {
JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
jdbcTokenRepository.setDataSource(dataSource);
return jdbcTokenRepository;
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.mvcMatchers("/node_modules/**")
.requestMatchers(PathRequest.toStaticResources().atCommonLocations());
}
}
当我测试的时候 Login
Postman 的api remember-me
cookie不存在。但是当我登录oauth2时,它会。
我在登录时阻止了重定向,但我想知道这是否与此有关(因为当我登录oauth2时,它会被重定向),我很好奇如何在我的开发环境中使用RememberMe。
暂无答案!
目前还没有任何答案,快来回答吧!