Spring Security实现用户动态菜单代码

1、SpringSecurity实现用户密码的加密和密码对比的方法,encode()方法用来加密数据,matches()用来对比加密数据和字符串是否一致

import org.junit.Test;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

public class passwordTest {
   
    @Test
    public void test1(){
   
        PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String encode="";
        for (int i = 0; i < 10; i++) {
   
            encode = passwordEncoder.encode("1234");
            System.out.println(encode);
        }
        System.out.println(passwordEncoder.matches("1234", encode));
    }

}

2、用户权限验证需要一个类实现UserDetailsService接口,类中从数据库中根据用户名查询出用户对象和角色权限数据,将权限授权给认证通过的用户,并返回一个具有功能权限的新用户对象

package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {
   
    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
   
        //在数据库中查询是否存在此用户,不存在return null,存在就给用户赋予权限
        User user=userService.findUserByUsername(username);
        if(user==null){
   
            return null;
        }
        //根据查询出来的用户数据给用户赋予权限
        List<GrantedAuthority>
  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值