spring security(2)自定义认证类+密码加密与识别

不可逆加密(hush算法)

可逆(密钥)

md5不可逆,但在线解密,是通过海量大数据里查出来,伪显示

bcrypt自动默认给你加盐(附加随机的随机数,同样的密码,但他能产生不同的密码串)

目录结构:

spring-security.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!--doubo有doubo的前缀,doker有doker前缀,security有security的前缀,beans,spring的前缀也是beans,不过默认省略了,给他配置前缀,不带前缀都是security的配置-->
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security.xsd">
    <!-- 相当于WebSecurityConfigurerAdapter中对应的方法. -->

    <!-- anto-config 为true将启用自动注册登录表单,基本身份验证,注销的URL,注销服务 -->
    <!-- protected void configure(HttpSecurity http) 用于配置路径以及全选. -->
<!--    页面拦截规则,pattern匹配路径/*不包括根目录,/**指所有,access角色名称,必须大写ROLE_开头这种格式,必须拥有role_user才有权限访问/*的资源
    不配user-expression,,不启用spel表达式,则就要写成access="hasRole('ROLE_USER')",默认<http use-expressions="true">,则要写成hasRole('ROLE_USER')
    还能匹配ip-->
    <!--该页面不登陆也能访问,配置允许授权的页面-->
    <http pattern="/*.html" security="none"/>
    <http pattern="/css/**" security="none"/>
    <http pattern="/img/**" security="none"/>
    <http pattern="/js/**" security="none"/>
    <http pattern="/plugins/**" security="none"/>
  <!--  <http pattern="/login.html" security="none"/>
    <http pattern="/fail.html" security="none"/>-->
    <http use-expressions="false">
       <!-- ROLE大写,故后面最好也是大写-->
        <!-- 拦截所有的url access 调用一个函数, true为通过,false为拒绝. 这里是要求有ROLE_USER角色 -->
        <intercept-url pattern="/**" access="ROLE_USER" />
       <!-- 开启表单登陆-->
       <!-- 自定义表单登陆的页面,成功跳转后的页面,,将资源地址从/**里面排除掉--><!--<form-login login-processing-url="/dimLogin"/>自定义验证表单的提交路径,则form action="dimLogin"-->
       <!-- <form-login username-parameter="dimUsername" password-parameter="dimPasswordName" always-use-default-target="true"总是跳到默认页面/>则<input name="dimUsername"/><input name="dimPassword/>"-->
        <form-login login-page="/login.html" default-target-url="/index.jsp" authentication-failure-url="/fail.html" />
       <!-- 头页面要jsp,他能带x-xsfr,,存在跨域,跨站访问,进学校要带牌,证明你是学校的人,防止csrf攻击,html没有x-xsfr,故要关闭小红牌验证机制-->
        <csrf disabled="true"/>
       <!-- 框架选项里面有个策略-->
       <!-- 如果两个页面的协议,端口(如果有指定)和域名都相同,则两个页面具有相同的源SAMEORIGIN同源策略。,加入配置,则允许跨域请求-->
        <headers>
            <frame-options policy="SAMEORIGIN"></frame-options>
        </headers>
      <!--  //自动产生默认/logout的地址,自定义退出登陆后要跳转的页面<logout logout-url="dimLogouturl" logout-success-url="dimLogin.html"></logout> 自定义退出y页,-->
        <!--前端<a href="../logout">退出登陆</a>就实现退出登陆功能了-->
        <logout/>
    </http>

    <!-- 相当于 protected void configure(AuthenticationManagerBuilder auth) 主要配置使用什么来进行连接.
    认证管理器,authentication-provider认证的提供者,认证什么,提供什么-->
    <authentication-manager alias="authenticationManager">
       <!-- 配置让他走这个类-->
        <authentication-provider user-service-ref="userDetailService">
          <!--  <user-service>
                &lt;!&ndash; 使用内存用户存储提供认证,这里先提前配置了一个系统的权限用户,权限为user的角色
                 配置当前系统的用户,authorities角色身份&ndash;&gt;
                <user authorities="ROLE_USER" name="abc" password="abc" />
               &lt;!&ndash; <user authorities="ROLE_USER" name="a" password="abc" />
                <user authorities="ROLE_USER" name="admin" password="abc" />&ndash;&gt;
            </user-service>-->
<password-encoder ref="passwordEncoding"/>
        </authentication-provider>
    </authentication-manager>
<beans:bean id="userDetailService" class="com.lmj.service.UserDetailsServiceImpl"></beans:bean>
<beans:bean id="passwordEncoding" class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"></beans:bean>
</beans:beans>

从数据库查询出正确的用户名,密码,与角色:的服务类:UserDetailsServiceImpl

package com.lmj.service;

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;

public class UserDetailsServiceImpl implements UserDetailsService {

    @Override
   // 传过来的username是用户登陆穿过来的,我们通过配置,在存到数据库
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("经过了UserDetailsServiceImpl");
       //用户名不存在,密码不对,则返回null
        //当前用户拥有那些角色,它是一个集合
        //它代表每一个角色GrantedAuthority,构建角色列表,挪到认证类中
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        //当前用户没有角色,故调用add方法,添加角色,但grantedAuthorities是一个接口,我们需要调用它的实现类SimpleGrantedAuthority来new一个用户
      //  有个构造方法,构造一个角色列表
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_USER"));
           //     返回当前用户对象,当密码,用户名相同,则放行
      //  返回的是正确的用户信息,返回到前端,框架自动和提交上来的用户信息进行匹配
        return new User("admin","123",grantedAuthorities);
    }
}

查询当前登陆的用户名:loginController:

package com.lmj.controller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
//获取用户登陆的用户名
@RestController
@RequestMapping("/login1")
public class LoginController {
    @RequestMapping("/name")
    public Map name(){
        String name= SecurityContextHolder.getContext().getAuthentication().getName();
        Map map=new HashMap<>();
        map.put("loginName",name);
        return map;
    }
    @RequestMapping("/add")
    public void add(String password){
        BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
        String password1=bCryptPasswordEncoder.encode(password);
        Map map=new HashMap();
        map.put("password",password1);
        System.out.println(password1);
    }
}

运行即可:

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值