简体   繁体   English

Spring Security安全自定义页面

[英]Spring Security secure custom pages

Is there a way to configure Spring Security (with Java config) in order to secure custom pages only, or even work upon @PreAuthorized annotation? 有没有一种方法可以配置Spring Security(使用Java配置)以仅保护自定义页面,甚至可以使用@PreAuthorized注释?

The idea is that I want to secure custom calls like /admin and other stuff (without hardcoding every call in the security configuration), which is set up in the controller under the mentioned annotation, but the other stuff shouldn't use authentication at all. 我的想法是,我想保护自定义调用(例如/admin和其他内容(不对安全配置中的每个调用进行硬编码),这些都在控制器中通过上述注释设置,但是其他内容完全不应该使用身份验证。

I had a hard time finding something which would work for me. 我很难找到适合自己的东西。 That does the trick and it's also very readable. 这可以解决问题,而且可读性也很高。

@Override
protected void configure(HttpSecurity http) throws Exception
{
    http.authorizeRequests()
            .antMatchers("/admin/**").access("hasRole('ADMIN')")
            .antMatchers("/**").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin();
}

and the full Class for those who are still not on the same page 以及仍不在同一页面上的人员的完整课程

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");
    }
}

Note that not calling the formLogin() method would make the default "/login" return a 404 error. 请注意,不调用formLogin()方法会使默认的“ / login”返回404错误。

I am not sure if this answers your question, but you could use ant matchers to identify certain pages and ignore others in your security configuration, like so: 我不确定这是否能回答您的问题,但是您可以使用蚂蚁匹配器来识别某些页面,而忽略安全配置中的其他页面,例如:

.antMatchers("/**").permitAll()

or 要么

.antMatcher("/admin/**")
.authorizeRequests()
.anyRequest().authenticated() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM