有没有办法配置 Spring Security(使用 Java 配置)以仅保护自定义页面,甚至可以使用 @PreAuthorized
注释?
我的想法是,我想要保护诸如 /admin
之类的自定义调用和其他内容(无需对安全配置中的每个调用进行硬编码),这些调用是在 Controller 中提到的注释下设置的,但是其他东西根本不应该使用身份验证。
最佳答案
我很难找到适合我的东西。这很有效,而且可读性也很强。
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
}
以及全类对于那些仍然不在同一页面上的人
package com.your.package.config;
import org.springframework.beans.factory.annotation.Autowired;
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
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
@Override
protected void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ADMIN')")
.antMatchers("/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
}
请注意,不调用 formLogin()
方法将使默认的“/login”返回 404 错误。
关于java - Spring Security 安全自定义页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36655794/