首页 > 其他分享 >spring security使用实例

spring security使用实例

时间:2023-05-30 15:23:24浏览次数:33  
标签:http configure admin spring void class 实例 security public

下面是一个使用Java和Spring Security的详细示例代码。该示例演示了如何设置身份验证和授权规则,并保护特定的URL路径。请注意,这只是一个基本示例,您可以根据自己的需求进行修改和扩展。

首先,确保您已经安装了Java开发环境(JDK)和Maven构建工具。

接下来,我们将创建一个Maven项目,并在项目的pom.xml文件中添加以下依赖项:

<dependencies>
    <!-- Spring Boot -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
        <version>2.5.0</version>
    </dependency>
    <!-- Spring Security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        <version>2.5.0</version>
    </dependency>
</dependencies>

接下来,创建一个Spring Boot应用程序,并创建以下文件。

DemoApplication.java - 启动类

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

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

HomeController.java - 控制器

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "Welcome to the home page!";
    }

    @GetMapping("/admin")
    public String admin() {
        return "Welcome to the admin page!";
    }
}

SecurityConfig.java - 安全配置

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN") // 保护/admin路径,要求具有ADMIN角色
                .anyRequest().authenticated() // 其他路径需要身份验证
                .and()
            .formLogin() // 使用表单登录
                .and()
            .httpBasic(); // 启用基本身份验证
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER") // 创建一个名为"user"的用户,密码是"password",具有USER角色
                .and()
                .withUser("admin").password("{noop}password").roles("ADMIN"); // 创建一个名为"admin"的用户,密码是"password",具有ADMIN角色
    }
}

SecurityConfig.java中,我们使用configure(HttpSecurity http)方法配置了URL的访问规则和安全策略。在configure(AuthenticationManagerBuilder auth)方法中,我们使用内存认证配置了两个用户。

最后,在`src/main/resources/application

.properties`文件中添加以下配置:

spring.security.user.password.encoder=none

这将禁用密码编码,以便我们可以使用明文密码进行演示。在实际应用中,您应该使用适当的密码编码器。

现在,您可以运行应用程序并访问以下URL:

  • http://localhost:8080/ - 欢迎页面,无需身份验证。
  • http://localhost:8080/admin - 管理员页面,需要具有ADMIN角色的身份验证。

在浏览器中访问这些URL时,您将被重定向到登录页面。使用以下用户进行身份验证:

  • 用户名:user,密码:password(具有USER角色)
  • 用户名:admin,密码:password(具有ADMIN角色)

根据用户的角色,您将被授权或拒绝访问相应的页面。

这是一个基本的Spring Security示例,您可以根据需要进行修改和扩展。


更多功能

当然!这里有更多的Spring Security示例代码,以展示不同的功能和用例。

  1. 使用数据库进行身份验证:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
    }

    // ...
}

在这个例子中,我们使用UserDetailsService从数据库中获取用户信息进行身份验证。

  1. 自定义登录页面:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .permitAll();
    }

    // ...
}

在这个例子中,我们指定了自定义的登录页面路径为/login,并允许所有用户访问该页面。

  1. 使用记住我功能:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

    // ...
}

在这个例子中,我们启用了记住我功能,允许用户在关闭浏览器后仍然保持登录状态。

  1. 限制登录尝试次数:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .authenticationProvider(authenticationProvider())
            .userDetailsService(userDetailsService());
    }

    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService());
        provider.setLockoutPolicy(new ExcessiveAttemptsLockoutPolicy());
        provider.setPreAuthenticationChecks(new UserDetailsChecker() {
            @Override
            public void check(UserDetails user) {
                // 自定义的用户验证逻辑
            }
        });
        return provider;
    }

    // ...
}

在这个例子中,我们使用DaoAuthenticationProvider设置了一个锁定策略,当用户登录尝试次数过多时会被锁定。

这些示例代码展示了Spring Security的不同功能和用例,您可以根据需要进行修改和扩展。


更多功能

当然!这里有更多的Spring Security示例代码,以展示不同的功能和用例。

  1. 为不同角色设置访问权限:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

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

    // ...
}

在这个例子中,我们根据用户的角色设置了不同的访问权限。具有ADMIN角色的用户可以访问/admin/**路径,具有USER角色的用户可以访问/user/**路径,其他路径需要身份验证。

  1. 使用CSRF保护:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf()
                .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                .and()
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin();
    }

    // ...
}

在这个例子中,我们启用了CSRF(Cross-Site Request Forgery)保护,使用CookieCsrfTokenRepository将CSRF令牌存储在Cookie中。

  1. 使用JWT进行身份验证:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/public").permitAll()
                .antMatchers("/api/private").authenticated()
                .and()
            .apply(new JwtConfigurer(jwtTokenProvider));
    }

    // ...
}

在这个例子中,我们使用JWT(JSON Web Token)进行身份验证。我们定义了公共和私有的API路径,并使用自定义的JwtConfigurer配置了JWT验证。

  1. 使用注解进行方法级别的授权:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
            .formLogin();

        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin();

        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .formLogin();
    }

    @Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public static class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
    }

    // ...
}

在这个例子中,我们使用@PreAuthorize注解和@EnableGlobalMethodSecurity配置了方法级别的授权,以允许在方法上定义访问规则。

这些示例代码展示了Spring Security的不同功能和用例,您可以根据需要进行修改和扩展。如果您有特定的需求或问题,请告诉我,我将

为您提供更多帮助。

标签:http,configure,admin,spring,void,class,实例,security,public
From: https://www.cnblogs.com/lukairui/p/17443336.html

相关文章

  • gradle使用实例
    以下是一个详细的Gradle示例代码,用于构建和管理Java项目:build.gradle文件:plugins{id'java'}group'com.example'version'1.0-SNAPSHOT'sourceCompatibility=1.8repositories{mavenCentral()}dependencies{implementation'......
  • memcache使用实例
    以下是一个详细的Java示例代码,用于使用Memcached进行缓存操作:首先,您需要在Java项目中添加对spymemcached库的依赖项。您可以使用Maven或Gradle等构建工具添加以下依赖项:Maven依赖项(将以下代码添加到pom.xml文件中):<dependencies><dependency><groupId>net.spy</gr......
  • 钉钉日志推送实例
    背景:jeecgboot集成钉钉小程序,进行日志填报,同时推送到钉钉日志系统给相关人员。主要方便日志问题的讨论,回复等。效果: 接口:通过数据ID查找封装Marckdown方式进行推送;publicStringdoLogsDataDingtalk(StringtableId,StringtoUsers){    if(!thirdAppConfig.......
  • SpringSecurity 添加验证码的两种方式
    一验证码生产<dependency><groupId>com.github.penggle</groupId><artifactId>kaptcha</artifactId><version>2.3.2</version></dependency>@ConfigurationpublicclassKaptchaConfig{@BeanPro......
  • springboot使用jdbc连接mysql(不用配置文件)
     1、连接mysql的工具类:packagecom.jzproject.common.mysql;importcom.alibaba.fastjson.JSON;importcom.alibaba.fastjson.JSONArray;importorg.springframework.jdbc.core.JdbcTemplate;importjava.sql.*;importjava.util.ArrayList;importjava.util.HashMap;......
  • Spring Boot 错误和异常处理
    在realtimeapplication开发中,我们使用Exceptionhandlingconcept,以平滑终止程序。它将systemerrormessages转换为userfriendlyerrormessages。但是在SpringBoot框架中,他们已经实现了Exceptionhandlingconcept,这里我们需要了解SpringBoot框架内部如何处......
  • SpringBoot集成RocketMQ,rocketmq_client.log日志文件配置
    SpringBoot项目集成rocketmq-client<dependency><groupId>org.apache.rocketmq</groupId><artifactId>rocketmq-client</artifactId><version>4.7.0</version></dependency>项目启动时会在${user.home}/logs目录下创建一个roc......
  • SpringMVC
    本次文章是我的springmvc学习的笔记,是观看尚硅谷的视频,欢迎大家去学习观看:https://www.bilibili.com/video/BV1Ry4y1574R/?vd_source=f38047c43021f07cf7a4e84b564bde02一、SpringMVC简介1.1什么是MVCMVC是一种软件架构的思想,将软件按照模型、视图、控制器来划分M:Model,模......
  • 非常不错的springboot启动shell脚本
    #!/bin/bashJAVA_OPTIONS_INITIAL=-Xms256MJAVA_OPTIONS_MAX=-Xmx256M_JAR_KEYWORDS=/wls/appsystem/ruoyi/apps/ruoyi-admin.jarAPP_NAME=ruoyi-adminAPPLICATION_FILE=/wls/appsystem/ruoyi/config/application.propertiesAPPLICATION_YAML_FILE=/wls/appsystem/ruoyi......
  • SpringSecurity集成启动报 In the composition of all global method configuration,
    一.异常内容Causedby:org.springframework.beans.factory.BeanCreationException:Errorcreatingbeanwithname'methodSecurityMetadataSource'definedinclasspathresource[org/springframework/security/config/annotation/method/configuration/GlobalMet......