springSecurity配置和相关API

首先进行pom文件配置

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

Config类的配置

在这里插入图片描述

通过连接数据库上的数据进行验证和授权

这是配置类

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//    @Bean
//    public PasswordEncoder passwordEncoder(){
//        return new BCryptPasswordEncoder();
//    }
@Autowired
private UserDetatlsServiceImpl  userDetatlsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       auth.userDetailsService(userDetatlsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //进行授权
        http.csrf().disable().authorizeRequests()
                .antMatchers(
                        "/index.html",
                        "/img/*",
                        "/js/*",
                        "/css/*",
                        "/login.html",
                        "/register.html",
                        "/register",
                        "/bower_components/**"
                ).permitAll()//全部允许
                //需要认证的
                .anyRequest().authenticated().and().formLogin()//采用表单进行认证
        .loginPage("/login.html")//展示验证表单
        .loginProcessingUrl("/login")//处理登陆的路径
        .failureUrl("/login.html?error")//登陆失败的路径
        .defaultSuccessUrl("/index.html")//登陆成功的页面
        .and().logout()//等处
        .logoutUrl("/logout")//等处的路径
        .logoutSuccessUrl("/login.html?logout")//登出成功访问的路径
        ;
    }
}

这个类是被UserDetailsImp类调用而获取UserDetailsImp对象的类

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
@Autowired
private UserMapper userMapper;
    @Override
    public UserDetails getUserDetails(String username) {
        User user = userMapper.findUserByUsername(username);
        if (user==null){
            return null;
        }
        List<Permission> list = userMapper.findUserPermissionsById(user.getId());
        int i = 0;
        String[]  authorities=new String[list.size()];
        for (Permission p : list) {
            authorities[i++]=p.getName();
        }
        UserDetails u= org.springframework.security.core.userdetails.User.builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .accountLocked(user.getLocked()==1)
                .disabled(user.getEnabled()==0)
                .authorities(authorities)
                .build();
        return u;
    }
}

获取用户信息

 public String currentUsername() {
        //利用springSecurity框架获得用户信息
      Authentication authentication =  SecurityContextHolder.getContext().getAuthentication();
      //检查是否为匿名登陆
      if (!(authentication instanceof AnonymousAuthenticationToken)){
          String  username = authentication.getName();
          return username;
      }
       throw ServiceException.notFound("还没有 登陆!!!");
    }

springSecurity测试组件

 <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
             <scope>test</scope>
        </dependency>

权限验证(比较)

@RestController
@Slf4j
public class HomeController {
    static final GrantedAuthority STUDENT =  new SimpleGrantedAuthority("ROLE_STUDENT");
    static final GrantedAuthority TEACHER =  new SimpleGrantedAuthority("ROLE_TEACHER");

    @GetMapping("/index.html")
    public ModelAndView index(@AuthenticationPrincipal User user){
        log.debug("用户信息为:{}",user);
        if (user.getAuthorities().contains(STUDENT)) {
            return new ModelAndView("index");
        }else if(user.getAuthorities().contains(TEACHER)){
            return new ModelAndView("index_teacher");
        }
       throw ServiceException.notFound("没有找到权限");
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值