Spring-boot & spring.security

时间:2022-05-14 05:10:21

spring.security提供了一种身份认证框架,开发者可以在这个框架中实现各种方式的用户身份管理,比如:LDAP、MYSQL、OAUTH、Mongo等等。

spring.security认证步骤:

1、配置类 WebSecurityConfigurerAdapter

该类中通过configure 各种参数来关联前端页面提交的身份信息和后端数据服务提供的身份信息。其中,

1)configure( HttpSecurity http)配置前端,各种页面的访问权限和登录页、用户名、密码的绑定信息

http.authorizeRequests()
.antMatchers("/", "/public/**").permitAll()
.antMatchers("/users/**").hasAuthority("ADMIN")
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.usernameParameter("email")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("remember-me")
.logoutSuccessUrl("/")
.permitAll()
.and()
.rememberMe();

2)configure(AuthenticationManagerBuilder auth)配置关联后端的身份数据信息提供源

    //DAO模式
@Autowired
private UserDetailsService userDetailsService; @Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(new BCryptPasswordEncoder());
}

spring.security在认证过程中调用userDetailsService实例的loadUserByUsername获取后端对应的身份认证信息,如果找不到则抛出UsernameNotFoundException

异常。

2. Controller中配置API的授权访问约束

      @PreAuthorize("@currentUserServiceImpl.canAccessUser(principal, #id)")
@RequestMapping("/user/{id}")
public ModelAndView getUserPage(@PathVariable Long id) {
... } @PreAuthorize("hasAuthority('ADMIN')")
@RequestMapping(value = "/user/create", method = RequestMethod.GET)
public ModelAndView getUserCreatePage() {