栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

[3天速成Spring Security] - 01 认证和授权

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[3天速成Spring Security] - 01 认证和授权

什么是认证和授权 认证(Authentication)

解决“我是谁”的问题

授权(Authorization)

解决“我能做什么”的问题

构建Spring Security Sample项目 构建项目
  • 到spring start io上面创建项目
  • 引入spring-boot-starter-web和spring-boot-starter-security依赖
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '2.5.5'
    // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-security', version: '2.5.5'
  • 添加Test API
@RestController()
@RequestMapping("/test")
public class TestController {

    @GetMapping("/01")
    public String firstApi() {
        return "Hello World";
    }
}
认证
  • 当添加spring security starter后,访问API时会默认重定向spring security默认登录页面/login
  • 查看启动日志的默认密码以及user为用户名登录后即可访问API
授权
  • 简单自定义角色授权的资源判断:继承WebSecurityConfigurerAdapter并重写configure方法,且通过@EnableWebSecurity注解标识当前类,内部逻辑按需构建
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 给/test/01 API添加权限判断,只有当有Admin的Role用户才可以访问
       http.authorizeHttpRequests(req -> req.mvcMatchers("/test/01").hasRole("Admin"));
}

此时如果登录用户没有Admin权限,当访问API时则会出现403错误

  • 重新实现简单判断逻辑:判断API是通过登录页认证过的,都可以授权访问
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 不检查权限,只检查是否是通过登录页面认证过的API
        http
                .formLogin(Customizer.withDefaults())
                .authorizeHttpRequests(req -> req.mvcMatchers("/test/01").authenticated());
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/294101.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号