spring boot整合SpringSecurity-02 基于Serssion的认证

spring boot整合SpringSecurity 目录

spring boot整合SpringSecurity-01入门
spring boot整合SpringSecurity-02 基于Serssion的认证
spring boot整合SpringSecurity-03 自定义报错信息
spring boot整合SpringSecurity-04 使用jwt的方式认证

基于Serssion的认证

上一章,我们讲了Spring Security自带的登录,但是我们一般都是使用自己制作的。
想要关闭Spring Security自带的登录,如下:
要在继承 WebSecurityConfigurerAdapter 的类下面

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
* SecurityConfig    登录认证的配置
*
* @创建人 江枫沐雪
* @创建时间 2021/6/20 17:17
*/
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
   private UserDetailsServiceImpl userDetailsService;

 //查询用户信息
   @Override
   protected void configure(AuthenticationManagerBuilder  auth) throws Exception {
       //用户详情信息
       auth.userDetailsService(userDetailsService)
               //密码加密方式
               .passwordEncoder(bCryptPasswordEncoder);
   }
   //密码加密方式
   @Bean
   public BCryptPasswordEncoder bCryptPasswordEncoder() {
   	return new BCryptPasswordEncoder();
   }

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       // @formatter:off
       http
               //配置跨域请求 并且 关闭打开的csrf保护
               .cors().and().csrf().disable()
//                 认证配置
               .authorizeRequests()
//                 登录验证等放行
                   .antMatchers("/auth/**","/app/**").permitAll()
//                 剩下的接口都需要登陆后访问
                   .anyRequest().authenticated()
               .and()
               //表单登录
                   .formLogin()
//                   用户未登录的的时候跳转的这个路径
//                    .loginPage("/home")
//                   用户登录时,用户名、密码提交的目的路径
                   .loginProcessingUrl("/login")
//                   用户成功登录以后
                   .successForwardUrl("/success")
               .and()
                   .logout()
                   .logoutUrl("/logout")
   }

}

二、实现UserDetailsService

import com.jiang.login.pojo.Permission;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


import java.util.List;

/**
 * MyUserDetailsService
 *
 * @创建人 江枫沐雪
 * @创建时间 2021/7/25 15:42
 */
@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    UserService userService;

    /**
     * 按用户名查询用户
     * @param username      用户名
     * @return
     * @throws UsernameNotFoundException
     */  
     @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户名是:{}",username);
        //查询用户
        com.jiang.login.pojo.User user = userService.getUserByUsername(username);
        // 根据用户编号查询
        List<Permission> perm = permissionService.getPermissionByUserId(user.getUserId());
        String[] per = new String[perm.size()];
        int i = 0;
        for (Permission p:perm){
            per[i] = p.getPermission();
            i++;
        }
//		向userDetails中写入已查询到的用户名和密码
        UserDetails userDetails = User.withUsername(user.getUsername())
                .password(user.getPassword())
                //权限写入
                .authorities(per).build();
        return userDetails;
    }
}

三、当然这里面实体类、sql语句、前端界面

这些我就不写了!
所以想要使用Spring Security 只需要两个配置。

  1. 继承 WebSecurityConfigurerAdapter 的类中写上一些拦截配置。
  2. 实现 UserDetailsService 的类中写入你从数据库中查询的用户名和密码,以及权限。
  3. 之后Spring Security 会自动的拦截比对密码。

四、授权

在实现 UserDetailsService 的类中写入你数据库中的权限。
想要进行授权拦截,就需要在你的方法上写上注解。

@RestController

public class Test {

    @PostMapping("success")
    private String success(){
        return "成功登录!";
    }
    
    
    @PostMapping("per")
    @PostAuthorize("hasAuthority('per')")
    private String per(){
        return "有权限访问!";
    }

}

当然如果你不写的话就是,必有权限拦截,都可以访问。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值