java - Spring Security 安全自定义页面

标签 java spring security spring-mvc spring-security

有没有办法配置 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/

相关文章:

java - Sonarqube 给我提供了删除代码的问题并且无法过滤问题

java - eddystone 信标在一段时间后自动断开连接并且不发送主要和次要

java - 寻找 JShell 输入解决方法

php - 在数据库中有一个大表安全吗?

security - 无需密码即可保护登录系统

java - Java 中的时间码

java - 并发使用 JaxWsPortProxyFactoryBean

java - Autowiring 两个实现相同接口(interface)的 bean - 如何将默认 bean 设置为 Autowiring ?

java - Spring属性优先

security - 保护网站管理部分的最佳做法是什么?