基于Spring Security认证授权的管理系统之Spring Security初使用

190 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第4天,点击查看活动详情

首先,我们介绍一下认证和授权:

  • 认证解决的是“我是谁”的问题

认证(Authentication):

典型的一个认证就是一个登陆过程,通过用户名和密码完成登陆认证。

image.png

  • 授权解决的是“我能做什么”的问题 对于一些稍微复杂的系统,网站拥有不用的用户,区分不同用户需要对用户进行权限进行限制。

image.png

下面介绍一下简单的Spring Security的应用。首先,建立如下一个目录

image.png

编写UaaApplication.java代码

package com.waitingfish.uaa;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class UaaApplication {
    public static void main(String[] args) {
        SpringApplication.run(UaaApplication.class, args);
    }
}

当我们不引入Spring Security时,直接访问http://localhost:8080/api/greeting ,这时候页面直接打开为

image.png

但是我们在pom文件中引入Spring Security后,

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- 用于测试 -->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

再次访问会发现,网站被拦截了,转到了登录页面。

image.png

默认中配置的用户名为user,生成的密码在项目启动时,控制台中会打印密码:

image.png

通过用户名、密码登录后,可以成功访问对应的网页:

image.png

我们通过以下代码对访问的页面添加权限认证:

import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests(req->req.mvcMatchers("api/greeting").hasAnyRole("ADMIN"));
    }
}

再次访问页面湖发现出现错误代码403,表示访问权限不足:

image.png