Java Spring Security认证与授权及注销和权限控制篇综合解析

yizhihongxing

Java Spring Security认证与授权及注销和权限控制篇综合解析

什么是Java Spring Security?

Spring Security是一个基于Spring框架的安全性框架,目的是为了帮助开发者构建安全性的应用。它提供了诸如认证,授权,攻击防御等安全特性。

认证

Spring Security 认证提供了选择、实现不同的认证方式。本节介绍三种常见的认证方式。

基本认证

基本认证是最简单的认证方式。客户端发起请求时,在“Authorization”头部传递Base64字符串,该字符串是由“username:password”组成,即用户名和密码,服务器根据该字符串来鉴别请求的合法性。

使用Spring Security实现基本认证:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .httpBasic();
}

表单认证

表单认证是Web应用中常见的认证方式。客户端在表单中填写用户名和密码,绑定提交,服务器端验证用户名和密码的正确性。

使用Spring Security实现表单认证:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable() // 禁用 CSRF
        .authorizeRequests()
        .antMatchers("/login").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login") // 登录页面
        .defaultSuccessUrl("/home")
        .permitAll()
        .and()
        .logout()
        .permitAll();
}

OAuth2.0认证

OAuth2.0是一种认证和授权标准,在应用程序中广泛使用。通过OAuth2.0认证,用户可以使用第三方服务进行登录。使用OAuth2.0认证需要调用第三方API,获取OAuth Token。

使用Spring Security实现OAuth2.0认证:

@Configuration
@EnableWebSecurity
@EnableOAuth2Sso
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .oauth2Login();
    }
}

授权

Spring Security 提供了丰富的授权方式,可以提供诸如基于角色、基于权限、ACL等授权特性,可满足各种复杂的授权需求。

基于角色授权

基于角色的授权是指用户通过分配角色来完成授权。系统管理员可以为用户分配角色,用户可以根据自己权限进行操作。

使用Spring Security实现基于角色的授权:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/home")
        .permitAll()
        .and()
        .logout()
        .permitAll();
}

基于权限授权

基于权限的授权是指用户通过分配权限来完成授权。系统管理员可以为用户分配权限,用户可以根据自己权限进行操作。

使用Spring Security实现基于权限的授权:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/admin/**").hasAuthority("ADMIN")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/home")
        .permitAll()
        .and()
        .logout()
        .permitAll();
}

注销

注销是将当前用户从系统中退出,Spring Security 提供了注销的实现。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/home")
        .permitAll()
        .and()
        .logout()
        .logoutUrl("/logout") // 注销URL
        .logoutSuccessUrl("/login") // 注销成功跳转URL
        .invalidateHttpSession(true)
        .deleteCookies()
        .permitAll();
}

权限控制

Spring Security 还提供了许多其他的功能,例如:权限控制、攻击防御等。

访问控制

对某些资源的访问进行控制,例如:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/admin/**").hasRole("ADMIN")
        .antMatchers("/user/**").hasRole("USER")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/home")
        .permitAll()
        .and()
        .logout()
        .permitAll();
}

CSRF防护

Spring Security 提供了CSRF防护来防护跨站请求伪造攻击,可以使用csrf().disable()禁用CSRF。

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable() // 禁用CSRF
        .authorizeRequests()
        .antMatchers("/login").permitAll()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/home")
        .permitAll()
        .and()
        .logout()
        .permitAll();
}

以上是Spring Security 认证与授权及注销和权限控制篇综合解析。

示例

基本认证

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello() {
        return "hello";
    }
}


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .httpBasic();
    }
}

使用curl工具请求:

curl --user user:password http://localhost:8080/hello

OAuth2.0认证

@SpringBootApplication
@RestController
@EnableOAuth2Sso
public class ClientApplication {
    @GetMapping("/")
    public String index(Principal principal) {
        return "Hello, " + principal.getName();
    }

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

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: ***
            client-secret: ***
            scope:
              - email
              - profile
        provider:
          google:
            authorization-uri: https://accounts.google.com/o/oauth2/v2/auth
            token-uri: https://www.googleapis.com/oauth2/v4/token
            user-info-uri: https://www.googleapis.com/oauth2/v3/userinfo
            user-name-attribute: name

请求:

浏览器中访问:http://localhost:8080/

可以看到授权页面,确认授权,成功后会返回页面显示用户信息。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Java Spring Security认证与授权及注销和权限控制篇综合解析 - Python技术站

(0)
上一篇 2023年5月20日
下一篇 2023年5月20日

相关文章

  • JSP 开发之servlet中调用注入spring管理的dao

    下面是关于 JSP 开发中在 Servlet 中调用注入 Spring 管理的 DAO 的完整攻略: 1. Maven 依赖 首先,在 pom.xml 文件中添加以下依赖: <!– Spring Framework –> <dependency> <groupId>org.springframework</gro…

    Java 2023年6月16日
    00
  • 一个合格的程序员应该读过哪些书(偏java)

    一个合格的程序员应该读过哪些书(偏 Java) 作为一名合格的程序员,阅读技术书籍是必不可少的,本文将为大家介绍几本值得程序员阅读的 Java 书籍。 基础篇 《Java核心技术 卷1+卷2》 这是 Java 开发者学习 Java 语言核心知识的第一本书,它的第一卷全面讲解了 Java 语言中的基础概念和关键技术,第二卷则着重介绍 Java 的高级特性。无论…

    Java 2023年5月20日
    00
  • java中\t,\n,\r,\b,\f 的作用及说明

    当我们在Java程序中编写字符串时,可能会使用一些特殊字符来表示某些特殊的字符或操作。在Java中,一些特殊字符会有特殊的含义和作用。以下是Java中一些常用的特殊字符: \t:制表符 制表符\t用于在输出中设置水平制表位置。它将当前输出位置移到下一个制表符位置,这样下一个字符将在该位置打印。示例代码如下: System.out.println("…

    Java 2023年5月26日
    00
  • java随机生成字符串(字符随机生成类 生成随机字符组合)

    生成随机的字符串在Java开发中是比较常见的需求,可以用于验证码生成、密码加密等场景。下面是一个完整的攻略,可以让您方便地实现这一功能。 1. 使用Java内置库实现随机字符串 Java提供了一个类 java.util.UUID,使用该类可以方便地生成随机的字符串。UUID是根据时间戳、硬件地址等信息生成的一串字符串,具有很高的唯一性。 示例代码如下: im…

    Java 2023年5月26日
    00
  • 微信小程序是什么语言开发的 微信小程序的开发语言介绍

    微信小程序是一种轻量级应用(小程序),通过微信平台进行发布和使用。微信小程序的开发使用的主要语言是JavaScript,同时也支持HTML和CSS。 在微信小程序开发中,需要使用微信提供的基础库(WXML、WXSS和基于JavaScript的逻辑代码)来实现页面的设计和交互功能。同时,微信小程序也支持使用第三方框架进行开发,例如使用Vue.js框架进行开发。…

    Java 2023年5月23日
    00
  • Java Web开发之MD5加密用法分析

    Java Web开发之MD5加密用法分析 什么是MD5加密 MD5全称为“Message-Digest Algorithm 5”,是一种非常常见并且安全性较高的哈希算法。MD5算法的核心在于将任意长度的数据(消息)通过一个不可逆的算法变换成一个固定长度的、十六进制表示的字符串,称为消息摘要。这个摘要具有防篡改性、密钥敏感性和抗碰撞等特性。 MD5加密的应用场…

    Java 2023年5月19日
    00
  • SpringBoot中整合MyBatis-Plus的方法示例

    Sure,下面是SpringBoot整合MyBatis-Plus的方法示例完整攻略: 一、前置准备 JDK 1.8+ Maven 3.0+ SpringBoot 2.0+ MyBatis-Plus 3.1.0+ 二、项目搭建 1. 创建SpringBoot项目 通过 Spring Initializer,创建一个 SpringBoot 项目,并导入 Mave…

    Java 2023年5月20日
    00
  • Springboot如何去掉URL后面的jsessionid

    要去掉Spring Boot应用程序中URL后的JSESSIONID,可以在servlet过滤器中进行配置,具体步骤如下: 创建一个过滤器类,并实现javax.servlet.Filter接口。 @Component public class JSessionIdFilter implements Filter { @Override public void…

    Java 2023年5月20日
    00
合作推广
合作推广
分享本页
返回顶部