springsecurity oauth2.0 通过注解跳过认证_Spring Security从入门到精通教程,企业开发首选Spring Security深入浅出...
时间: 2023-07-25 17:17:46 浏览: 110
Spring Security+OAuth2 精讲,打造企业级认证与授权
3星 · 编辑精心推荐
您好,关于在 Spring Security 中通过注解跳过认证,可以使用 `@PermitAll` 注解来标注不需要认证的接口或方法,具体实现如下:
1.在 Spring Security 配置类中开启注解支持:
```java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// ...
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// ...
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/public/**"); // 配置静态资源放行
}
@Bean
public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler() {
DefaultWebSecurityExpressionHandler webSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
webSecurityExpressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator()); // 权限校验器
return webSecurityExpressionHandler;
}
@Bean
public MethodSecurityExpressionHandler methodSecurityExpressionHandler() {
// 方法级别的权限校验
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setPermissionEvaluator(new CustomPermissionEvaluator()); // 权限校验器
return expressionHandler;
}
@Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return methodSecurityExpressionHandler();
}
@Override
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// ...
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
```
2.在接口或方法上使用 `@PermitAll` 注解:
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
@PreAuthorize("hasPermission(#id, 'user', 'read')")
@PermitAll // 标注不需要认证
public ResponseEntity<User> getUserById(@PathVariable Long id) {
User user = userService.getUserById(id);
return ResponseEntity.ok(user);
}
}
```
以上就是通过注解在 Spring Security 中跳过认证的实现方法,希望能对您有所帮助。
阅读全文