Spring Security-SecurityContext不持久

时间:2019-02-22 20:44:39

标签: spring security

我对Spring Security有问题。基本上,当我进行登录(手动身份验证)时,可以设置身份验证,但是如果我再次执行此请求,则该身份验证就消失了(我得到403)...如果我使用permitAll()该端点,则可以看到我得到的委托人是anonymousUser

我的春季会议:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {


@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authProvider());
}

@Override
protected void configure(HttpSecurity http) throws Exception {

    http
            .csrf()
                .disable()
            .authorizeRequests()
                .antMatchers("/user/login/").permitAll()
                .antMatchers("/user/register/").permitAll()
                .anyRequest().authenticated();

}

@Bean
public AuthProvider authProvider() {
    return new AuthProvider();
}

@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
    return super.authenticationManagerBean();
}

@Bean
public PasswordEncoder encoder() {
    return new BCryptPasswordEncoder(12);
}
}

我的登录控制器(及其逻辑管理器):

@PostMapping("/login")
@ResponseBody
public UserLoginResponse login(@RequestBody UserLogin userLogin, HttpServletResponse response, HttpServletRequest req) {

    UserLoginResponse resp;

    resp = new UserLoginResponse();

    logger.info(MessageFormat.format("CALLED - Login from user {0}", userLogin.getUsername()));

    resp.setId(userLogicManager.login(userLogin, req));

    if (resp.getId() == -1) {
        response.setStatus(HttpStatus.NOT_FOUND.value());
        logger.info(MessageFormat.format("ERROR - Login failed user {0}", userLogin.getUsername()));
    }

    System.out.println(securityManager.checkUser());

    return resp;
}

经理

public Long login(UserLogin userLogin, HttpServletRequest req) {

    DiginuUser diginuUser;
    Long res = new Long(-1), currTime;
    Date loginDate;

    logger.info(MessageFormat.format("LOGIC - Login diginuUser {0}", userLogin.getUsername()));

    loginDate = new Date();
    currTime = loginDate.getTime();

    diginuUser = userRepository.findUserByEmail(userLogin.getUsername());

    if (diginuUser != null) {

      //  if(passwordEncoder.matches(userLogin.getPassword(),diginuUser.getPassword())) {


            diginuUser.setLastLogin(new Timestamp(currTime));
            userRepository.save(diginuUser);
            res = diginuUser.getId();

            UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(userLogin.getUsername(), userLogin.getPassword());

            Authentication auth = authenticationManager.authenticate(authReq);

            SecurityContext sc = SecurityContextHolder.getContext();
            sc.setAuthentication(auth);

           createNewHttpSession(req,sc);

            logger.info(MessageFormat.format("LOGIC - COMPLETED - Login diginuUser {0}", userLogin.getUsername()));
    //    }
    }

    return res;
}

我通常不检查密码是否匹配(编码器出现问题)。

我的身份验证提供者:

   package com.uands.diginu.security;

    public class AuthProvider implements AuthenticationProvider, Serializable    {

    @Autowired
    UserRepository userRepository;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    public boolean supports(Class<? extends Object> authentication) {
        return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String username = authentication.getName();
        String password = (String) authentication.getCredentials();
        UsernamePasswordAuthenticationToken authToken = null;

        try {
            DiginuUser user = userRepository.findUserByEmail(username);

            //if(passwordEncoder.matches(password, user.getPassword())) {

            password = "";
            List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("USER"));

            authToken = new UsernamePasswordAuthenticationToken(username, password, grantedAuths);

            // }

        } catch (Exception e) {
            throw new AccessDeniedException("An error occurred during authentication");
        }

        return authToken;
    }
}

0 个答案:

没有答案