[Spring Cloud] - Spring Security实践(一)- 基本概念及实践

暗物质计算
• 阅读 1902

基本使用

Spring security需要的基本依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

其他部分不需要任何的增加。

Security的理论是两个核心:认证(我是谁)和鉴权(我能做什么)。
在code中,这两个核心都需要通过继承WebSecurityConfigurerAdapter来实现。

➡️废话不多说,上代码

首先,确保yml中添加了上面提到的两个依赖。添加后这就是最基本的spring security工程了。

然后,我们可以先添加一些controller。比如IndexController

@RestController
public class IndexController{
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(){
        return "index";
    }
}

此时启动项目,会发现启动log中夹杂着一句乱码:

Using generated security password: 2465a939-a37d-4d3e-9ee1-05d2e51f18fb

这个“乱码”就是spring security提供的缺省密码。
此时访问项目url,会自动跳转到项目url/login页面。
[Spring Cloud] - Spring Security实践(一)- 基本概念及实践
默认username为user, password栏输入刚刚那一句“乱码”。
点击signin,发现跳转成功,会访问到我们最初访问的页面。

自定义用户名密码 - 第一种内存模式

创建@configuration:

新建一个类,继承 WebSecurityConfigurerAdapter, 添加注解@EnableWebSecurity (不用再添加@Configuration注解,因为已被EnableWebSecurity包含)如下所示。

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
}

覆写父类方法:

覆写configure(AuthenticationManagerBuilder auth)方法
⚠️ 父类中包含多个configure方法,注意选择正确方法。代码如下所示:

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
            .withUser("user").password(new BCryptPasswordEncoder().encode("123")).roles("USER");
}

此方法实现了三个功能:

  1. 定义了用户名和密码(user/123)
  2. 加密了密码 - ⚠️ springsecurity强制密码加密,此处必须这样写
  3. 定义此用户的role为USER - Spring security根据role来做鉴权操作,此处只是认证,暂时忽视即可。

此时,重启项目,已经看不到最开始那一串乱码了,使用user/123登陆,即可跳转至正确页面。

自定义用户名密码 - 第二种内存模式

**此处注意,security 5.0之后的版本,需要在密码前加上加密格式。
所以仅仅使用BCryptPasswordEncoder将密码encode还不够,还要在encode后的密码前方加上密码格式。**

官方说明:

The general format for a password is:
 
{id}encodedPassword
Such that id is an identifier used to look up which PasswordEncoder should be used and encodedPassword is the original encoded password for the selected PasswordEncoder. The id must be at the beginning of the password, start with { and end with }. If the id cannot be found, the id will be null. For example, the following might be a list of passwords encoded using different id. All of the original passwords are "password".
 
{bcrypt}$2a$10$dXJ3SW6G7P50lGmMkkmwe.20cQQubK3.HZWzG3YB1tlRy.fqvM/BG 
{noop}password 
{pbkdf2}5d923b44a6d129f3ddf3e3c8d29412723dcbde72445e8ef6bf3b508fbf17fa4ed4d6b99ca763d8dc 
{scrypt}$e0801$8bWJaSu2IKSn9Z9kM+TPXfOc/9bdYSrN1oD9qfVThWEwdRTnO7re7Ei+fUZRJ68k9lTyuTeUp4of4g24hHnazw==$OAOec05+bXxvuu/1qZ6NUR+xQYvYv7BeL1QxwRpY5Pc=  
{sha256}97cde38028ad898ebc02e690819fa220e88c62e0699403e94fff291cfffaf8410849f27605abcbc0
@Configuration
public class AuthConfiguration {
 @Bean
 public UserDetailsService userDetailsService(){
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        String password = new BCryptPasswordEncoder().encode("123");

// 正确的结果
manager.createUser(User.withUsername("user").password("{bcrypt}" + password).roles("USER").build());
       
// 错误  
manager.createUser(User.withUsername("admin").password(password).roles("ADMIN").build());
// 错误     
manager.createUser(User.withUsername("all").password(password).roles("USER", "ADMIN").build());
        return manager;
    }
}

鉴权

覆写方法
鉴权依靠的是另一个方法: configure(HttpSecurity http),注意:其中httpSecurity代表一整套过滤器链,每个过滤器表示一个配置项。
代码如下:

@Override
    protected void configure(HttpSecurity http) throws Exception {
    }

示例代码及注释如下:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
         // 匹配 "/","/index" 路径,不需要权限即可访问
        .antMatchers("/user/user1").permitAll()
         // 匹配 "/admin" 及其以下所有路径,都需要 "USER" 权限
        .antMatchers("/admin/**").hasRole("USER")
        .and()
        // 登录地址为 "/login",登录成功默认跳转到页面 "/user"
        .formLogin().loginPage("/login").defaultSuccessUrl("/user/user1")
        .and()
        // 退出登录的地址为 "/logout",退出成功后跳转到页面 "/login"
        .logout().logoutUrl("/logout").logoutSuccessUrl("/login");
}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
美凌格栋栋酱 美凌格栋栋酱
6个月前
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
3年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
3年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
JVM 字节码指令表
字节码助记符指令含义0x00nop什么都不做0x01aconst\_null将null推送至栈顶0x02iconst\_m1将int型1推送至栈顶0x03iconst\_0将int型0推送至栈顶0x04iconst\_1将int型1推送至栈顶0x05ic
Python进阶者 Python进阶者
1年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这