栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot整合springsecrity的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot整合springsecrity的使用

本人小菜鸡 见谅

pom配置
    
            org.springframework.boot
            spring-boot-starter-security
        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        
        
            org.thymeleaf.extras
            thymeleaf-extras-springsecurity5
        
config配置
package com.hexu.demo3.config;

import com.hexu.demo3.service.impl.UserDetailsServiceImpl;
import com.hexu.demo3.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;


@EnableWebSecurity  //开启
@Configuration
public class SpringSecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Resource
    UserDetailsServiceImpl userDetailsServiceImpl;

    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //数据库是明文的话按下面就行了
        //auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(new BCryptPasswordEncoder());

        //数据库不是明文  我用的是MD5加密
        auth.userDetailsService(userDetailsServiceImpl).passwordEncoder(new PasswordEncoder() {

            @Override
            public String encode(CharSequence charSequence) {
                return MD5Util.getMD5((String) charSequence);
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return s.equals(MD5Util.getMD5((String) charSequence));
            }
        });
    }


    //权限认证
    @Override
    protected void configure(HttpSecurity http) throws Exception {
//给页面添加认证    不同级别进入不同的页面  antMatchers(“页面”) hasRole(“角色”)
        http.authorizeRequests().antMatchers("/", "/lo").permitAll()
                .antMatchers("/vip").hasAnyRole("VIP", "SSVIP", "SVIP")
                .antMatchers("/svip").hasAnyRole("SVIP", "SSVIP")
                .antMatchers("/ssvip").hasRole("SSVIP");
        //没有登录返回自带的登录页面  loginPage(“自定义登陆页面”)
        http.formLogin().loginPage("/lo").loginProcessingUrl("/login").successForwardUrl("/").failureUrl("/lo").permitAll();
        //启动记住我功能  rememberMeParameter(“跟登陆页面的记住我复选框name值一致”)
        http.rememberMe().rememberMeParameter("remember");
        //退出页面  logoutSuccessUrl退出的地址
        http.logout().logoutSuccessUrl("/").invalidateHttpSession(true).deletecookies();

        // 关闭 csrf 防护
        http.csrf().disable();

    }
}
//权限列名值要以  ROLE_开头   hasRole(ROLE_后面的权限)

工具类

md5加密

package com.hexu.demo3.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Util {
    
    public final static String getMD5(String str){
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");//创建具有指定算法名称的摘要
            md.update(str.getBytes());                    //使用指定的字节数组更新摘要
            byte mdBytes[] = md.digest();                 //进行哈希计算并返回一个字节数组

            String hash = "";
            for(int i= 0;i 
service 
package com.hexu.demo3.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hexu.demo3.dao.UserDao;
import com.hexu.demo3.pojo.User;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    UserDao userDao;
    @Override
    public UserDetails loadUserByUsername(String s) throws AuthenticationException  {
        QueryWrapper queryWrap=new QueryWrapper<>();
        queryWrap.eq("name",s);
        User user = userDao.selectOne(queryWrap);
        Assert.notNull(user,"账号不存在");
       //权限
        List vip = AuthorityUtils.commaSeparatedStringToAuthorityList(user.getRake());
        //  没有用MD5加密就用这个      new BCryptPasswordEncoder().encode(user.getPass())
        return new org.springframework.security.core.userdetails.User(user.getName(),user.getPass(),vip);
    }
}

controller
package com.hexu.demo3.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class hello {

    @RequestMapping("/")
    public String home() {
        return "home";
    }

    @RequestMapping("/lo")
    public String lo() {
        return "login";
    }

    @RequestMapping("/vip")
    public String vip() {
        return "vip";
    }

    @RequestMapping("/svip")
    public String svip() {
        return "svip";
    }

    @RequestMapping("/ssvip")
    public String ssvip() {
        return "ssvip";
    }
}

前端页面 home.html



  
  Title





用户名 角色 退出
vip通道 svip通道 大王vip通道
login.html



    
    Title


账号 密码 记住我
ssvip.html



    
    Title


恭喜SSVIP进入



svip.html



    
    Title


恭喜SVIP进入



vip.html



    
    Title


恭喜VIP进入


结果 登陆页面

svip用户登陆

ssvip用户登陆

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/695505.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号