springboot+security 内存中读取账号密码 自定义加密规则

一、项目地址:

码云地址:https://gitee.com/huatao1994/springbootSecurity/tree/master

二、项目结构:

up-e77818a5714c51e9413a4664a2808f8ded2.png

三、controller

1、 UserController

package cn.**.security.controller;

import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * @ProjectName: springbootSecurity
 * @Package: cn.**.security.controller
 * @Author: huat
 * @Date: 2019/12/12 14:56
 * @Version: 1.0
 */
@RestController
public class UserController {

    //@Secured("ROLE_ADMIN")//security权限注解
    //@RolesAllowed("ROLE_ADMIN") //jsr250注解
    //@PreAuthorize("hasRole('ROLE_ADMIN')")//spring的注解
    @RequestMapping("/login")
    public String login(String username,String password){
        //获取登陆的用户名
        String username1= SecurityContextHolder.getContext().getAuthentication().getName();
        System.out.println(username);
        return "index";
    }
    @RequestMapping("test")
    public String test(){
        return "你好这里是test页面";
    }


}

2、IntoController

package cn.**.security.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @ProjectName: springbootSecurity
 * @Package: cn.**.security.controller
 * @Author: huat
 * @Date: 2019/12/16 15:16
 * @Version: 1.0
 */
@Controller
public class IntoController {

    @RequestMapping("intoTest")
    public String intoTest(){
        return "/test";
    }
    @RequestMapping("intoIndex")
    public String intoIndex(){
        return "index";
    }
    @RequestMapping("intoFail")
    public String intoFail(){
        return "fail";
    }
    @RequestMapping("intoLogin")
    public String intoLogin(){
        return "login";
    }

    @RequestMapping("dologin")
    public String dologin(){
        return "index";
    }

}

三、util

1、MyPasswordEncoder

package cn.**.security.util;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;

/**
 * @ProjectName: springbootSecurity
 * @Package: cn.**.security.util
 * @Author: huat
 * @Date: 2019/12/13 17:14
 * @Version: 1.0
 * 自定义加密类
 */
@Component
public class MyPasswordEncoder implements PasswordEncoder {
    private static final String SALT = "jzd,.,.";

    /**
     * 加密
     * @param charSequence 需要加密的密码
     * @return
     */
    @Override
    public String encode(CharSequence charSequence) {
        charSequence = charSequence + SALT;
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        char[] charArray = charSequence.toString().toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuffer hexValue = new StringBuffer();
        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }

            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

    /**
     * 判断加密后的密码是否一致
     * @param charSequence 需要加密的密码
     * @param password    数据库中加密后的密码,权限框架会直接传入
     * @return
     */
    @Override
    public boolean matches(CharSequence charSequence, String password) {
        String pwd=encode(charSequence);
        if(pwd.equals(password)){
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        MyPasswordEncoder passwordEncoder=new MyPasswordEncoder();
        System.out.println(passwordEncoder.encode("123456"));
    }
}

2、SpringSercurityConfig

package cn.**.security.util;


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.method.configuration.EnableGlobalMethodSecurity;
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;


/**
 * @ProjectName: springbootSecurity
 * @Package: cn.**.security.util
 * @Author: huat
 * @Date: 2019/12/14 8:06
 * @Version: 1.0
 */

/**
 * 开启security注解支持
 * @EnableWebSecurity
 * (securedEnabled=true) 开启@Secured 注解过滤权限
 * (jsr250Enabled=true)开启@RolesAllowed 注解过滤权限
 * (prePostEnabled=true) 使用表达式时间方法级别的安全性         4个注解可用
 * @EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true,jsr250Enabled=true)
 */
@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled=true,jsr250Enabled=true)
public class SpringSercurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 将账号密码设置在内存当中
     * @param auth
     * @throws Exception
     */
    @Override
    public  void configure(AuthenticationManagerBuilder auth) throws Exception {
        //从内存中获取账号密码
        auth.inMemoryAuthentication()
                //设置账号
                .withUser("admin")
                //设置,密码{noop}代表明文
                .password(passwordEncoder.encode("1"))
                //配置类中加角色不能有前缀
                .roles("USER");
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        //释放静态资源,指定资源拦截规则,
        // 指定自定义认证页面,指定退出认证配置,csrf(跨域伪造请求)配置
        http.authorizeRequests()
                .antMatchers("intoLogin","login.jsp","/css/**","fail.jsp","/intoIndex","/index.jsp").permitAll()//释放这些资源,允许匿名访问
               .antMatchers("/**").hasAnyRole("ADMIN","USER")
                .anyRequest().authenticated()//其他资源需要认证
                .and()
                .formLogin()
                .loginPage("/intoLogin")//登陆页请求的接口
                .loginProcessingUrl("/dologin")//登陆地址,由springSecurity提供
                .successForwardUrl("/intoTest")//登陆成功
                .failureForwardUrl("/intoFail")//登录失败
                .permitAll()//指定所有资源释放
                .and()
                .logout()//登出
                .logoutUrl("/logout")//指定登出路径
                .logoutSuccessUrl("/intoLogin")//登出成功后跳转的url
                .invalidateHttpSession(true)//是否清空session
                .permitAll()
                .and()
                .csrf()
                .disable();//关闭csrf(跨域伪造请求)
    }
}

四、jsp页面

1、首页

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/12/16
  Time: 15:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<head>
    <title>测试</title>
</head>
<body>
ceshi
<security:authentication property="name"></security:authentication>
<!--动态显示   满足USER角色才能看到-->
<security:authorize access="hasRole('USER')">
可以看到
</security:authorize>
</body>
</html>

2、登陆页

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019/12/16
  Time: 15:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page isELIgnored="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<html>
<body>

<form method="post" action="/dologin">
    name:<input name="username">
    password:<input name="password">
    <input type="submit">
</form>
</body>
</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半夜燃烧的香烟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值