Java --- springboot3整合springSecurity

一、整合springSecurity

 引入pom依赖

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

config配置类 

@EnableMethodSecurity
@Configuration
public class MySecurityConfig {
    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        //请求授权
        httpSecurity.authorizeHttpRequests(registry->{
            registry.requestMatchers("/").permitAll()//首页都能访问
                    .anyRequest().authenticated();//除首页外都需要认证
        });
        //表单登录:使用springSecurity默认表单登录
        //httpSecurity.formLogin();
        //使用自己的登录
        httpSecurity.formLogin(httpSecurityFormLoginConfigurer -> {
            httpSecurityFormLoginConfigurer.loginPage("/login").permitAll();//自定义登录页位置
        });
        return httpSecurity.build();
    }
    //查询用户详情
    @Bean
    UserDetailsService userDetailsService(PasswordEncoder passwordEncoder){
        UserDetails laowang = User.withUsername("laowang")
                .password(passwordEncoder.encode("123456"))//密码必须加密
                .roles("admin")
                .authorities("file_read")
                .build();
        UserDetails zhangsan = User.withUsername("zhangsan")
                .password(passwordEncoder.encode("123456"))
                .roles("admin","hr")
                .authorities("file_write")
                .build();
        //模拟内存中保存所有用户信息
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager(laowang,zhangsan);
        return manager;
    }
    //密码加密器
    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}

前端界面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>你好呀</h1>
</body>
</html>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org">
<head>
  <title>Spring Security Example</title>
</head>
<body>
<div th:if="${param.error}">Invalid username and password.</div>
<div th:if="${param.logout}">You have been logged out.</div>
<form th:action="@{/login}" method="post">
  <div>
    <label> User Name : <input type="text" name="username" /> </label>
  </div>
  <div>
    <label> Password: <input type="password" name="password" /> </label>
  </div>
  <div><input type="submit" value="登录" /></div>
</form>
</body>
</html>

controller层

@RestController
public class HelloController {
    @GetMapping("/hello")
    public String hello(){
        return "hello";
    }
    @PreAuthorize("hasAuthority('file_write')")
    @GetMapping("/filed")
    public String filed(){
        return "获取写权限";
    }
}
@Controller
public class LoginController {
    @GetMapping("/login")
    public String login(){
        return "login";
    }

}

通过springboot配置文件配置

spring.security.user.name=laowang
spring.security.user.password=123456
spring.security.user.roles=admin,hr

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Spring Security OAuth2 Authorization Server 是一个基于 Spring Security 的 OAuth2 认证服务器,用于管理 OAuth2 模式下的授权和令牌。 要将 Spring Boot 与 Spring Security OAuth2 Authorization Server 集成,可以遵循以下步骤: 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.security</groupId> <artifactId>spring-security-oauth2-authorization-server</artifactId> <version>0.2.1</version> </dependency> ``` 2. 配置认证服务器 创建一个配置类,用于配置 OAuth2 认证服务器。这个类需要继承 AuthorizationServerConfigurerAdapter 类,并且实现 configure 方法。 ```java @Configuration public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { // 配置客户端信息 clients.inMemory() .withClient("client") .secret("{noop}secret") .authorizedGrantTypes("authorization_code", "refresh_token") .redirectUris("http://localhost:8080/client") .scopes("read", "write"); } @Override public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { // 配置安全性 security.checkTokenAccess("isAuthenticated()"); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { // 配置端点 endpoints.authenticationManager(authenticationManager); } } ``` 上面的代码中,我们配置了一个名为 "client" 的客户端,使用了授权码模式和刷新令牌模式。授权成功后,将重定向到 "http://localhost:8080/client" 页面。 3. 配置 Spring Security 为了使 OAuth2 认证服务器正常工作,需要配置 Spring Security。可以创建一个配置类,用于配置 Spring Security。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // 配置 HTTP 安全性 http.authorizeRequests() .antMatchers("/oauth2/authorize").authenticated() .and().formLogin().and().csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 配置身份认证管理器 auth.inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER"); } } ``` 在上面的代码中,我们配置了 HTTP 安全性和身份认证管理器。只有经过身份认证的用户才能访问 "/oauth2/authorize" 端点。 4. 启动应用程序 现在可以启动应用程序,并访问 "http://localhost:8080/oauth2/authorize?response_type=code&client_id=client&redirect_uri=http://localhost:8080/client" 来进行授权。授权成功后,将重定向到 "http://localhost:8080/client" 页面。 以上就是整合 Spring Boot 和 Spring Security OAuth2 Authorization Server 的基本步骤。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鸭鸭老板

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值