spring-security登录验证spring boot项目部署

一、pom.xml中导入资源jar

使用生成进行添加
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
</dependency>
外部导入
<dependency>
         <groupId>org.thymeleaf.extras</groupId>
         <artifactId>thymeleaf-extras-springsecurity5</artifactId>
         <version>3.0.4.RELEASE</version>
</dependency>

二、创建config配置类替代spring配置文件

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userService;

    /**
     * 配置信息放行资源
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //资源放行
        http.authorizeRequests().antMatchers("/login.html", "403.html", "/css/**", "/js/**", "/img/**", "/plugins/**").permitAll();

        //设置资源必须登录成功后进行访问
        http.authorizeRequests().antMatchers("/**").authenticated();

        //角色认证,角色名不加 ROLE_ ,系统自动添加
        http.authorizeRequests().antMatchers("/**").hasAnyRole("USER", "ADMIN");

        //设置登录页面
        http.formLogin().defaultSuccessUrl("/to/index")//登录成功
                .loginPage("/login.html")//设置登录页面,没有的话采用框架自带页面
                .loginProcessingUrl("/login")//登录url,固定login
                .usernameParameter("username")//账号
                .passwordParameter("password")//密码
                .failureUrl("/login.html");//登录失败

        //关闭跨域
        http.csrf().disable();

        //设置退出登录
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html");

        //配置403异常处理
        http.exceptionHandling().accessDeniedPage("/403.html");
    }
    
    /**
     * 认证数据管理:连接认证 service
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.userDetailsService(userService);
    }
}

三、创建service接口继承 UserDetailsService 类 ,实现类重写loadUserByUsername方法

public interface UserService extends UserDetailsService {

}

public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //调用持久层获取用户登录信息
         Users loginuser = userDao.findUserByUsername(username);

        User user = new User(loginuser.getUsername(),loginuser.getPassword(),loginuser.getStatus()==1,true,true,true,getRoles(loginuser.getRoleList()));
        return user;
    }

    /**
     * 封装用户角色
     * @param roleList
     * @return
     */
    private Collection<? extends GrantedAuthority> getRoles(List<Role> roleList) {

        ArrayList<GrantedAuthority> alist = new ArrayList<>();

        for (Role role : roleList) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
            alist.add(authority);
        }
        return alist;
    }
    @Bean
    //定义加密器
    public PasswordEncoder createPasswordEncoder(){

        return NoOpPasswordEncoder.getInstance();

    }
}

四、前端权限验证

<!DOCTYPE html>

//导入命名空间
<html lang="en" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
    <meta charset="UTF-8">
    <base href="http://localhost:8081/"/>
    <title>Title</title>
</head>
<body>
    这是主页

	标签进行授权认证
    <div sec:authentication="name"></div>
    <div sec:authorize="hasRole('ROLE_USER')">
        普通用户
    </div>

    <div sec:authorize="hasRole('ROLE_ADMIN')">
        管理员用户
    </div>

</body>
</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值