spring security controller层实现登陆

spring security controller层实现登陆

1,导入依赖

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

2,security配置类

项目github地址

security的登陆在过滤器中实现,在前后端分离下,我更希望能在controller层实现自己的登陆逻辑,这样加验证码啥的也更方便。

security的认证判断是通过authenticationManager去判断构造的UsernamePasswordToken,然后生成验证通过后Authentication,将这个Authentication放入SecurityContextHolder中即可实现认证。

所以我的实现思路为在controller层直接注入authenticationManager

配置类

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomerUserDetailService userDetailService;

    @Autowired
    private FindByIndexNameSessionRepository sessionRepository;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //禁用baisc和form认证,在AuthController中自己实现认证逻辑
                .httpBasic().disable()
                .formLogin().disable()
                .csrf().disable()
                .logout().disable()

        ;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {     auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    @Bean
    //注入authenticationManager
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public SpringSessionBackedSessionRegistry sessionRegistry() {
        return new SpringSessionBackedSessionRegistry(sessionRepository);
    }
}

controller

@RestController
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseMsg login(@RequestBody @Valid LoginRequest loginRequest, HttpSession session) {
        UsernamePasswordAuthenticationToken token =
                new UsernamePasswordAuthenticationToken(loginRequest.getUsernameOrEmail(), loginRequest.getPassword());
        Authentication authentication = authenticationManager.authenticate(token);
        SecurityContextHolder.getContext().setAuthentication(authentication)return ResponseMsg.success200("登陆成功");
    }

    @RequestMapping("test")
    @PreAuthorize("isAuthenticated()")
    public ResponseMsg test(){
        return ResponseMsg.success200("需要登陆才能访问的url");
    }

    @PreAuthorize("isAuthenticated()")
    @PostMapping("/logout")
    public ResponseMsg logout() {
        SecurityContextHolder.clearContext();
        return ResponseMsg.success200("退出成功");
    }


}

userDetailService

@Service
public class CustomerUserDetailService implements UserDetailsService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;


    @Override
    public UserDetails loadUserByUsername(String usernameOrEmai) throws UsernameNotFoundException {
        UserInfo userInfo = userDao.findByUsernameOrEmail(usernameOrEmai,usernameOrEmai)
                .orElseThrow(()-> new UsernameNotFoundException("用户不存在:"+usernameOrEmai));
        if (userInfo.getStatus().equals(Constant.USER.NOT_INVOKE)){
            throw new CustomerException("用户未激活,请先根据邮件激活");
        }
        UserPrincipal userPrincipal = new UserPrincipal();
        BeanUtil.copyProperties(userInfo,userPrincipal);
        userPrincipal.setRoles(roleDao.findRoleListByUserId(userInfo.getId()));
        return userPrincipal;
    }
}


userDetail

@AllArgsConstructor
@NoArgsConstructor
@Builder
public class UserPrincipal implements UserDetails {

    private Long id;

    private String username;

    private String password;

    private String nickname;

    private String email;

    private String phone;

    private String avatar;

    private LocalDateTime createTime;

    private List<Role> roles;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return AuthorityUtils
                .createAuthorityList(roles.stream().map(Role::getRoleName).toArray(String[]::new));
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }

    @JsonIgnore
    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    public void setUsername(String username) {
        this.username = username;
    }


    public void setPassword(String password) {
        this.password = password;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

}

你可能感兴趣的:(java,spring,security)