但使龙城飞将在,不教胡马度阴山

SpringBoot+SpringSecurity

整合了SpringSecurity权限框架

@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailServiceImpl userDetailService;

    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //登录页放开校验
        http.authorizeRequests()
                .antMatchers("/login.html", "/login").permitAll()
                .anyRequest().authenticated();
        //自动跳转登录页
       //定义了一个login请求用于跳转登陆页面
       http.formLogin().loginPage("/login").loginProcessingUrl("/login").defaultSuccessUrl("/success");
        //关闭csrf校验
        http.csrf().disable();
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //认证方法
            auth.userDetailsService(userDetailService).passwordEncoder(passwordEncoder());
    }

    //自定义加密方式
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

// auth.userDetailsService()
// 这个方法需要一个UserDetailsService接口的实现类,我们需要创建一个类来实现这个接口,
//并且重写loadUserByUsername方法,写入我们自己想要实现的逻辑,然后将该实现类放入ioc,在这个auth.userDetailsService()地方传入该实现类的实例对象
//使用注解将该对象放入容器中
@Component
public class UserDetailServiceImpl implements UserDetailsService {
    @Autowired
    private PasswordEncoder encoder;
    @Autowired
    private SystemService systemService;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User currUser =  systemService.getUserInfo(s);
        if (currUser == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        //加密过程在此处体现
        return new org.springframework.security.core.userdetails.User(currUser.getUserName(), encoder.encode(currUser.getPassword()),new ArrayList<>());
    }
}

用于跳转自定义登录页的请求

@RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(
    ) {
        try {
            return "login";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

前台页面流转暂时使用的是thymeleaf,仅用于测试SpringSecurity有效性,之后会改成Vue前后台分离项目

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org/" lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户登录</title>
</head>
<body>
<h1>用户登录</h1>
<form th:action="@{/login}" method="post">
    用户名:<input type="text" name="username"> <br>
    密码:<input type="text" name="password"><br>
    <input type="submit" value="登录">
</form>
</body>
</html>

现在访问未放开的接口,security都会自动跳转到我们自定义的登陆页面
在这里插入图片描述
登陆成功后,才可访问其他页面和请求
返回json
在这里插入图片描述
跳转页面
在这里插入图片描述

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值