Spring Security使用(三)

Spring Security的web权限控制方案 · 认证

一、认证的基础三种方式

(一)设置登录的用户名和密码

1.通过配置文件

在application.properties中,写上如下代码,即可设置用户名为tom,密码为123

#spring.security.user.name=tom
#spring.security.user.password=123

加入用户名和密码后,就不会在控制台自动生成密码,在登录界面,输入自定义的用户名tom和密码123即可访问成功
在这里插入图片描述

2.通过配置类

创建config包,创建SecurityConfig继承WebSecurityConfigurerAdapter,重写 protected void configure(AuthenticationManagerBuilder auth) ()方法
在这里插入图片描述
但是当如上图写好进行访问时,会出现如下报错,且浏览器页面没有反应

There is no PasswordEncoder mapped for the id “null”
表示PasswordEncoder匹配的id值为空,因为密码是进行加密过的,需要找寻PasswordEncoder对象解密,而默认是没有的。因此,解决办法就是配置出来,但是因为是一个借口,所以要new出来一个该接口的实现类:

package com.config;

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.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 配置类,配置登录的用户名和密码,密码进行加密
 * 用户名:jack
 * 密码:123
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
   
        //将密码进行加密
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String password = passwordEncoder.encode("123");
        //System.out.println(password);
        //设置登录信息
        auth.inMemoryAuthentication()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值