springboot个人项目之整合spring security

1、pom文件配置

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring security 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

2、自定义MyWebSecurityConfigurerAdapter,并继承WebSecurityConfigurerAdapter

package com.yc.ux.config;

import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class MyWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {

3、重写WebSecurityConfigurerAdapter的configure(AuthenticationManagerBuilder auth)和configure(HttpSecurity http)方法

》 configure(AuthenticationManagerBuilder auth)方法是用来配置用户签名服务,有三种方式

使用内存存储、使用数据库、自定义存储

  • 使用内存存储
/**
*
*使用内存存储
*/

//密码编辑器
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

auth.inMemoryAuthentication()
//设置密码编码器
.passwordEncoder(passwordEncoder)
//注册用户 admin , 密码为 abc ,并赋予 USER 和 ADMIN 的角色权限
.withUser("admin")
.password("$2a$10$vCG07AYgkRHNm2meEjfSeOpndOeGrcea4vMbJci9wNiZByX0CHjhi")
.roles("USER", "ADMIN")
.and()
//注册用户 myuser,密码为 12345 , 并赋予 USER 的角色权限
.withUser("myuser")
.password("$2a$10$JeESxunaQIHtyS2/JBkZsOcDsvcEQtv/lAOndxfBqIhzuYecHm5XC")
.roles("USER");
  •  使用数据库存储
@Autowired
private DataSource dataSource;

String pwdQuerySql = "SELECT uu.login_name, uu.login_pwd, (CASE WHEN uu.`status` = 'Y' THEN 1 ELSE 0" +
            " END) AS enabled FROM ux_user uu WHERE uu.login_name = ?";

    String roleQuerySql = "SELECT uu.login_name, ur.role_code from ux_user uu, ux_role ur, ux_role_user" +
            " uru WHERE uu.id = uru.user_id AND ur.id = uru.role_id AND uu.login_name = ?";

/**
* 使用数据库存储
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //密码编辑器
    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    auth.jdbcAuthentication()
    .passwordEncoder(passwordEncoder)
    .dataSource(dataSource)
    .usersByUsernameQuery(pwdQuerySql)
    .authoritiesByUsernameQuery(roleQuerySql);
}
  • 自定义存储

第一步:实现UserDetailService接口

package com.yc.ux.security;

import com.yc.ux.entity.Role;
import com.yc.ux.entity.UxUser;
import com.yc.ux.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 java.util.ArrayList;
import java.util.List;

/**
 * \* UxUser: YC
 * \* Date: 2019/5/23
 * \* Time: 23:45
 * \* Description:
 * \
 */
@Configuration
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserRoleService userRoleService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        UxUser user = userRoleService.getUserByName(userName);
        //获取数据库角色信息
        List<Role> roleList = userRoleService.findRolesByUserName(userName);
        return changeToUser(user, roleList);
    }

    private UserDetails changeToUser(UxUser uxUser, List<Role> roleList) {
        List<GrantedAuthority> authorityList = new ArrayList<>();
        for (Role role : roleList) {
            GrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleCode());
            authorityList.add(authority);
        }
        UserDetails userDetails = new User(uxUser.getLoginName(), uxUser.getLoginPwd(), authorityList);
        return userDetails;
    }
}

第二步:配置WebSecurityConfigurerAdapter

@Autowired
private UserDetailsService userDetailsService;

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    //密码编辑器
    PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    /**
    * 自定义存储
    */
    auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
}

》 configure(HttpSecurity http)方法用来配置每个用户拥有的角色所具有的权限

如果要配置自定义登录页面时,使用http.formLogin().loginPage("/login/page")

@Override
protected void configure(HttpSecurity http) throws Exception {
    //访问hello开头的路径需要有admin权限
    http.authorizeRequests().antMatchers("/hello/**").hasRole("admin");
    //当访问某一路径没有权限时,跳转到/login/page所代表的自定义登录页面
    http.formLogin().loginPage("/login/page");
}


@Controller
@RequestMapping("/login")
public class LoginController {

    /**
     * 如果是要跳转到login页面,一定不能配置@RestController或者在方法上配置@ResponseBody
     * @return
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
        public String login() {
            return "login";
        }
}

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录页面</title>
</head>
<body>
<h2>自定义登录页面</h2>
<form action="/login/page" method="post">
    <table>
        <tr>
            <td>用户名:</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密码:</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td colspan="2"><button type="submit">登录</button></td>
        </tr>
    </table>
</form>
</body>
</html>

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值