java spring 鉴权
时间: 2023-09-22 18:11:59 浏览: 63
在Spring框架中实现鉴权可以使用Spring Security。Spring Security是一个基于Spring的安全性框架,可以对应用程序进行认证和授权。下面是一个简单的示例:
1. 添加Spring Security依赖
```xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
```
2. 配置Spring Security
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/home")
.permitAll()
.and()
.logout()
.permitAll();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
}
```
在上面的配置中,我们关闭了CSRF防护,并配置了登录页面、成功页面和注销页面。我们还使用内存身份验证将用户名和密码硬编码为"user"和"password"。
3. 创建控制器
```java
@RestController
public class HomeController {
@GetMapping("/home")
public String home() {
return "Welcome home!";
}
@GetMapping("/admin")
@PreAuthorize("hasRole('ADMIN')")
public String admin() {
return "Welcome admin!";
}
}
```
在上面的控制器中,我们定义了两个端点:/home和/admin。/home不需要任何权限,而/admin要求用户必须有"ADMIN"角色才能访问。我们使用@PreAuthorize注释来实现这一点。
以上就是一个简单的Spring Security鉴权示例。当用户访问/admin时,如果用户没有正确的角色,将会得到一个403 Forbidden响应。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)