美文网首页
springboot 整合 springsecurity

springboot 整合 springsecurity

作者: 灰气球 | 来源:发表于2017-05-26 20:14 被阅读0次
  • spring-boot 整合 spring-security

    • maven 支持

              <!-- spring security 认证授权 -->
      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-security</artifactId>
      </dependency>
      
    • 配置文件

      @EnableWebSecurity
      public class MultiHttpSecurityConfig {
      
          @Configuration
          public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
      
              // 静态资源访问的 url
              private String[] staticFileUrl = {};
              // 不用认证就可访问的 url
              private String[] permitUrl = {};
      
              @Override
              public void configure(WebSecurity web) throws Exception {
                  web.ignoring().antMatchers(staticFileUrl);
                  web.ignoring().antMatchers(permitUrl);
              }
      
              @Override
              protected void configure(HttpSecurity http) throws Exception {
                  // 访问url认证
                  http
                          .authorizeRequests()
                          .antMatchers("/admin/**").hasAuthority(String.valueOf(AuthorityName.ROLE_ADMIN))
                          .anyRequest().authenticated();
                  // 配置登陆信息
                  http
                          .formLogin().loginPage("/login")
                          .defaultSuccessUrl("/goIndex")
                          .permitAll()
                          .and();
                  // 配置退出登陆信息
                  http
                          .logout()
                          .logoutSuccessUrl("/login")
                          .invalidateHttpSession(true)
                          .deleteCookies()
                          .and();
                  http.httpBasic();
              }
          }
      }
      
    • 使用 自己数据库的 用户信息,进行对登陆的form提交的信息,进行验证。验证成功后为该用户配置相应的权限。

      @Service
      public class UserDetailsServiceImpl implements UserDetailsService {
      
          @Autowired
          private UserRepository userRepository;
      
          @Override
          public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
              User user = userRepository.findByUserName(username);
      
              if (user == null) {
                  throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username));
              } else {
                  return JwtUserFactory.create(user);
              }
          }
      }
      
    • 注意:

      • 需要实现该接口:
        import org.springframework.security.core.userdetails.UserDetailsService;
      • 并实现方法:UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;
    • 至此,springboot 整合 springsecurity 已经完成,不过,对于权限认证,使用的是 form 表单提交登陆的方式。

相关文章