【问题标题】:Java annotation based Spring security config基于 Java 注解的 Spring 安全配置
【发布时间】:2018-02-13 06:19:16
【问题描述】:

我尝试基于 Spring security 配置进行 Java 注释。我在遵循教程并提供了代码后执行此操作,

@Configuration
@EnableWebSecurity
// need to change this to the security directory
@ComponentScan("")
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private MySavedRequestAwareAuthenticationSuccessHandler authenticationSuccessHandler;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {

        auth.inMemoryAuthentication()
                .withUser("temporary").password("temporary").roles("ADMIN")
                .and()
                .withUser("user").password("userPass").roles("USER");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint(restAuthenticationEntryPoint)
                .and()
                .authorizeRequests()
                .antMatchers("/api/foos").authenticated()
                .and()
                .formLogin()
                .successHandler(authenticationSuccessHandler)
                .failureHandler(new SimpleUrlAuthenticationFailureHandler())
                .and()
                .logout();
    }

    @Bean
    public MySavedRequestAwareAuthenticationSuccessHandler mySuccessHandler() {
        return new MySavedRequestAwareAuthenticationSuccessHandler();
    }

    @Bean
    public SimpleUrlAuthenticationFailureHandler myFailureHandler() {
        return new SimpleUrlAuthenticationFailureHandler();
    }
}

我工作的项目的API 基地,

public static final String API_BASE = "/*";

例如,我执行cURL 之类的请求,

curl -X GET http://localhost:8080/rest/wallet/wallets | json

我不确定代码中的 .antMatchers("/api/foos").authenticated() 行。例如,foos 来自哪里,我是否需要将其更改为 .antMatchers("/foos").authenticated()?

【问题讨论】:

    标签: java spring spring-mvc spring-security


    【解决方案1】:

    如果您是编程新手,这是一个有效的问题。不过习惯就好。所有示例通常都会有 'foo' 和 'bar' 作为示例变量、方法名称等。

    无论如何,.antMatchers("/api/foos").authenticated() 指定匹配 /api/foo 的模式 URL 需要经过身份验证,然后应该使用以下处理程序。

    将模式更改为您的匹配模式 - .antMatchers("/rest/wallet/**") 并测试您的代码。

    更多参考 - 阅读这篇文章:When to use Spring Security`s antMatcher()?

    【讨论】:

    • 所以我有@Path("rest/wallet")、@Path("rest/service") 和@Path("rest/user") 之类的路径,并且我使用了.antMatchers("rest/wallet/**").authenticated() .antMatchers("rest/user/**").authenticated() .antMatchers("rest/service/**").authenticated() 之类的匹配项。现在正确吗?告诉我,我会接受你的回答。
    • 对我来说似乎很好。只需使用 / 像 /rest/wallet 开始 URL 上下文路径(考虑在类顶部有根路径 @Path("/rest"),这样您就不必一直重复根上下文)。我只是给了你在哪里看的上下文。探索更多并继续前进。你被卡住的越多,你学到的就越多。 :)
    • 编程确实如此,有时你只是感觉不到推动更多的能量:)
    猜你喜欢
    • 2014-07-11
    • 1970-01-01
    • 2011-04-24
    • 2014-09-11
    • 2013-12-06
    • 1970-01-01
    相关资源
    最近更新 更多