spring security controller層が登録を実現しました。
spring security controller層が登録を実現しました。
1,導入依存
プロジェクトのgithubアドレス
securityの登録はフィルタの中で実現して、前後の端の分離の下で、私は更にcontrolerの階で自分の登録の論理を実現することができることを望んで、このようにコードを検証するのも更に便利です。
securityの認証は、authentication Managerによって構造のUsernamePasswordTokenを判断し、検証が通過した後にAuthenticationを生成し、このAuthenticationをSecurityContact Holderに入れて認証を行うことができます。
ですから、私はアウトレット層に直接authenticationManagerを注入するという考えを実現しました。
クラスの設定
1,導入依存
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2,security配置類プロジェクトのgithubアドレス
securityの登録はフィルタの中で実現して、前後の端の分離の下で、私は更にcontrolerの階で自分の登録の論理を実現することができることを望んで、このようにコードを検証するのも更に便利です。
securityの認証は、authentication Managerによって構造のUsernamePasswordTokenを判断し、検証が通過した後にAuthenticationを生成し、このAuthenticationをSecurityContact Holderに入れて認証を行うことができます。
ですから、私はアウトレット層に直接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);
}
}
制御装置@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(" ");
}
}
userDetail Service@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;
}
}