springsecurity自定义userService和认证逻辑(在springboot中)

看了一下感觉这东西还挺难的,得写点什么来总结一下。

1.要启用springsecurity很简单只需要在pom.xml中添加相关依赖就行了

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

2.准备User类和Role类,这里直接用JPA

@Entity(name = "t_user")
public class User implements UserDetails {    
               
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String username;

    private String password;

    private boolean accountNonExpired;

    private boolean accountNonLocked;

    private boolean credentialsNonExpired;

    private boolean enabled;

    @ManyToMany(fetch = FetchType.EAGER,cascade = CascadeType.PERSIST)
    private List<Role> roles;



    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for(Role role:getRoles()){
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        return authorities;
        
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    //下面是基本的getter和setter

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setAccountNonExpired(boolean accountNonExpired) {
        this.accountNonExpired = accountNonExpired;
    }

    public void setAccountNonLocked(boolean accountNonLocked) {
        this.accountNonLocked = accountNonLocked;
    }

    public void setCredentialsNonExpired(boolean credentialsNonExpired) {
        this.credentialsNonExpired = credentialsNonExpired;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public List<Role> getRoles() {
        return roles;
    }

    public void setRoles(List<Role> roles) {
        this.roles = roles;
    }
}

用户实体类主要需要实现 UserDetails 接口,并实现接口中的方法。

这里的字段基本都好理解,几个特殊的我来稍微说一下:

accountNonExpired、accountNonLocked、credentialsNonExpired、enabled 这四个属性分别用来描述用户的状态,表示账户是否没有过期、账户是否没有被锁定、密码是否没有过期、以及账户是否可用。
roles 属性表示用户的角色,User 和 Role 是多对多关系,用一个 @ManyToMany 注解来描述。
getAuthorities 方法返回用户的角色信息,我们在这个方法中把自己的 Role 稍微转化一下即可。
3.定义UserDao和UserService

public interface UserDao extends JpaRepository<User,Long> {

    User findUserByUsername(String username);
}

@Service
public class UserService implements UserDetailsService {
    @Autowired
    UserDao userDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userDao.findUserByUsername(username);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        return user;
    }
}

4.前端定义了一组页面,分别划归3个不同得权限暂且整三个vip1,vip2,vip3得权限吧
在首页中写了个table并放上三类页面的超链接

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org"
                xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <meta charset="UTF-8">
    <title>securitytest</title>
</head>
<body>
<table>
    <thead>
        <tr>
            <th>VIP1的内容</th>
            <th>VIP2的内容</th>
            <th>VIP3的内容</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><a th:href="@{/level1/rank1}">点击进入VIP1-1</a></td>
            <td><a th:href="@{/level2/rank2}">点击进入VIP2-1</a></td>

            <div sec:authorize="hasRole('ROLE_vip3')"> <td><a th:href="@{/level3/rank3}">点击进入VIP3-1</a></td> </div>
        </tr>
        <tr>
            <td><a th:href="@{/level1/rank1-2}">点击进入VIP1-2</a></td>
            <td><a th:href="@{/level2/rank2-2}">点击进入VIP2-2</a></td>
            <div sec:authorize="hasRole('ROLE_vip3')"><td><a th:href="@{/level3/rank3-2}">点击进入VIP3-3</a></td></div>
        </tr>
        <tr>
            <td><a th:href="@{/level1/rank1-3}">点击进入VIP1-3</a></td>
            <td><a th:href="@{/level2/rank2-3}">点击进入VIP2-3</a></td>
            <div sec:authorize="hasRole('ROLE_vip3')"><td><a th:href="@{/level3/rank3-3}">点击进入VIP3-3</a></td></div>
        </tr>
    </tbody>
</table>
<a th:href="@{/Login_page}">去登录</a>
<a th:href="@{/logout}">注销</a>
</body>
</html>

(PS)要使用thymeleaf和springsecurity的整合需要在pom.xml中添加如下依赖

		<dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>

登录页面可以是springsecurity提供的,也可以是自己写的,这里自己写一个简单的登录页面Login_page.html

<body>
<form th:action="@{/Login_page}" method="post">
    <span style="color: aqua;font-size: 36px;text-align: center">登录表单</span><br>
    <label>用户名:</label><input type="text" name="username" /><br>
    <label>密码:</label><input type="password" name="password"/><br>
    <input type="submit" value="登录"/>
</form>

之后写一个Controller去跳转这些页面
controller

@Controller
public class LoginController {

    @RequestMapping({"/","/index","/index.html"})
    public String toindex(){
        return "index";
    }
    @RequestMapping("/Login_page")
    public String toLogin(){
        return "Login_page";
    }

    @RequestMapping({"/level1/rank1","/level1/rank1.html"})
    public String level1rank1(){
        return "level1/rank1";
    }
    @RequestMapping({"/level1/rank1-2","/level1/rank1-2.html"})
    public String level1rank2(){
        return "level1/rank1-2";
    }
    @RequestMapping({"/level1/rank1-3","/level1/rank1-3.html"})
    public String level1rank3(){
        return "level1/rank1-3";
    }
    ////////////////////////////////////////////////////////////////////////
    @RequestMapping({"/level2/rank2","/level2/rank2.html"})
    public String level2rank1(){
        return "level2/rank2";
    }
    @RequestMapping({"/level2/rank2-2","/level2/rank2-2.html"})
    public String level2rank2(){
        return "level2/rank2-2";
    }
    @RequestMapping({"/level2/rank2-3","/level2/rank2-3.html"})
    public String level2rank3(){
        return "level2/rank2-3";
    }
    ///////////////////////////////////////////////////////////////////////
    @RequestMapping({"/level3/rank3","/level3/rank3.html"})
    public String level3rank1(){
        return "level3/rank3";
    }
    @RequestMapping({"/level3/rank3-2","/level3/rank3-2.html"})
    public String level3rank2(){
        return "level3/rank3-2";
    }
    @RequestMapping({"/level3/rank3-3","/level3/rank3-3.html"})
    public String level3rank3(){
        return "level3/rank3-3";
    }
    //////////////////////////////////////////////////////
}

在测试类中添加并运行如下代码,在数据库中留下记录

@SpringBootTest
class SpringsercuiryApplicationTests {

    @Autowired
    UserDao userDao;

    BCryptPasswordEncoder encoder;

    @Test
    void contextLoads() {
        encoder = new BCryptPasswordEncoder();
        User user = new User();
        List<Role> lihansrole = new ArrayList<>();
        lihansrole.add(new Role("ROLE_vip1","贵宾1"));
        lihansrole.add(new Role("ROLE_vip2","贵宾2"));
        lihansrole.add(new Role("ROLE_vip3","贵宾3"));
        user.setUsername("lihan");
        user.setPassword(encoder.encode("wdnmd"));
        user.setAccountNonExpired(true);
        user.setAccountNonLocked(true);
        user.setCredentialsNonExpired(true);
        user.setEnabled(true);
        user.setRoles(lihansrole);
        userDao.save(user);
        //////////////////////////////////////////////////////分割线
        User user1 = new User();
        List<Role> usersrole = new ArrayList<>();
        usersrole.add(new Role("ROLE_vip1","贵宾1"));
        usersrole.add(new Role("ROLE_vip2","贵宾2"));
        user1.setUsername("root");
        user1.setPassword(encoder.encode("wdnmd"));
        user1.setAccountNonExpired(true);
        user1.setAccountNonLocked(true);
        user1.setCredentialsNonExpired(true);
        user1.setEnabled(true);
        user1.setRoles(usersrole);
        userDao.save(user1);
        /////////////////////////////////////////////////////分割线
        User user2 = new User();
        List<Role> user2srole = new ArrayList<>();
        user2srole.add(new Role("ROLE_vip1","贵宾1"));
        user2.setUsername("guest");
        user2.setPassword(encoder.encode("wdnmd"));
        user2.setAccountNonExpired(true);
        user2.setAccountNonLocked(true);
        user2.setCredentialsNonExpired(true);
        user2.setEnabled(true);
        user2.setRoles(user2srole);
        userDao.save(user2);
    }

}

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
最后写一个springsecurity配置类

@EnableWebSecurity
public class securityconfiger extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth..userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
                
        
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                                .antMatchers("/index").permitAll()
                                .antMatchers("/vc.jpg").permitAll()
                                .antMatchers("/Login_page").permitAll()
                                .antMatchers("/level1/**").hasAnyRole("vip1")
                                .antMatchers("/level2/**").hasAnyRole("vip2")
                                .antMatchers("/level3/**").hasAnyRole("vip3");
        http.formLogin().loginPage("/Login_page").loginProcessingUrl("/Login_page");
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");
    }
}

完成后启动项目用不同的用户名密码登录,完成了认证和授权
(之后改了代码,加了验证码,自定义了认证逻辑,忘了截图了。。。。。)

下面自定义认证逻辑

1.添加一下kaptcha的maven依赖

		<dependency>
            <groupId>com.github.penggle</groupId>
            <artifactId>kaptcha</artifactId>
            <version>2.3.2</version>
        </dependency>

2.定义一个生成验证码的Controller,并把正确的验证码存入Session之中

@RestController
public class VerifyCodeController {

    @Autowired
    Producer producer;

    @GetMapping("/vc.jpg")
    public void getVerifyCodeImage(HttpServletResponse resp, HttpSession session) throws IOException {
        resp.setContentType("image/jpeg");
        String code = producer.createText();
        session.setAttribute("verifyCode",code);
        BufferedImage image = producer.createImage(code);
        try(ServletOutputStream out = resp.getOutputStream()){
            ImageIO.write(image,"jpg",out);
          }
    }

    @Bean
    public Producer VerityDode(){         //配置一下验证码
        Properties properties = new Properties();
        properties.setProperty("kaptcha.image.width","150");
        properties.setProperty("kaptcha.image.height","50");
        properties.setProperty("kaptcha.textproducer.char.string","0123456789");
        properties.setProperty("kaptcha.textproducer.char.length","4");
        Config config = new Config(properties);
        DefaultKaptcha defaultKaptcha = new DefaultKaptcha();
        defaultKaptcha.setConfig(config);
        return defaultKaptcha;

    }
}

定义MyAuthenticationProvider继承DaoAuthenticationProvider
并重写additionalAuthenticationChecks()方法添加验证码的逻辑

public class MyAuthenticationProvider extends DaoAuthenticationProvider {
    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        HttpServletRequest req = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();

        String input_code = req.getParameter("code");
        String verify = (String)req.getSession().getAttribute("verifyCode");
        if(input_code==null||verify==null||!input_code.equals(verify)){
            throw new AuthenticationServiceException("验证码错误");
        }
        super.additionalAuthenticationChecks(userDetails, authentication);
    }
}

之后需要改动一下security配置类

 @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.authenticationProvider(myAuthentication());
                
    }

    @Bean
    MyAuthenticationProvider myAuthentication(){
        MyAuthenticationProvider myAuthenticationProvider = new MyAuthenticationProvider();
        myAuthenticationProvider.setPasswordEncoder(new BCryptPasswordEncoder());
        myAuthenticationProvider.setUserDetailsService(userService);
        return myAuthenticationProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/").permitAll()
                                .antMatchers("/index").permitAll()
                                .antMatchers("/vc.jpg").permitAll()
                                .antMatchers("/Login_page").permitAll()
                                .antMatchers("/level1/**").hasAnyRole("vip1")
                                .antMatchers("/level2/**").hasAnyRole("vip2")
                                .antMatchers("/level3/**").hasAnyRole("vip3");
        http.formLogin().loginPage("/Login_page").loginProcessingUrl("/Login_page");
        http.csrf().disable();
        http.logout().logoutSuccessUrl("/");
    }
}

再稍微改一下登录页就行了

<body>
<form th:action="@{/Login_page}" method="post">
    <span style="color: aqua;font-size: 36px;text-align: center">登录表单</span><br>
    <label>用户名:</label><input type="text" name="username" /><br>
    <label>密码:</label><input type="password" name="password"/><br>
    <label>验证码</label><input type="text" name="code">
    <input type="submit" value="登录"/>
</form>
<div>
    <img th:src="@{/vc.jpg}" style="width: 150px;height: 50px" />
</div>

再次启动项目
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
登录一下最低权限的账号
请添加图片描述
请添加图片描述
请添加图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

罗马苏丹默罕默德

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值