gpt4 book ai didi

javascript - 当使用 AngularJS 登录后授权 header 不存在时,Spring Security 不会抛出错误

转载 作者:行者123 更新时间:2023-11-29 19:11:29 25 4
gpt4 key购买 nike

我关注 Spring Security and Angular JS对于 HTTP 基本身份验证,通过将 Authorization header 添加到 $http header :

const headers = {
authorization: "Basic " + btoa(this.login + ":" + this.password)
};

this._$http.get("user",
{
headers: headers,
})
.then(
this.showUser.bind(this),
this.showError.bind(this)
);

showUser 中,我使用 $location 重定向到 jobs 组件:

this._$location.path("jobs");

jobs 组件中,我加载可用的作业:

public $onInit() {
this._$http.get("jobs").then(function(response) {
this.jobs = response.data;
}.bind(this));
this.authenticated = this._loginService.isLogged();
}

故意未经授权 header ,以证明一切正常。我认为它应该被 Spring SecurityHTTP 401 Unauthorized 或类似的东西放弃,但它在没有授权 header 的情况下工作。当我从另一个浏览器窗口注销并重新加载作业时,没问题,作业没有加载。但我认为(并且我希望)授权数据(HTTP Basic)应该出现在每个请求中。这是我的安全配置:

protected void configure(HttpSecurity http) throws Exception {
http
.formLogin()
.successHandler(
new DifferentRoleBasedStartingURLsAuthenticationSuccessHandler()
)
.and()
.logout()
.logoutUrl("/logout")
.and()
.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/jobs/**").authenticated()
.antMatchers("/interviews/**").authenticated()
.anyRequest().permitAll()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
;

也许我在这里犯了一个错误。我认为规则 .antMatchers("/jobs/**").authenticated() 应该使 jobs/ 也通过身份验证。你能帮助我吗?先感谢您。


2016 年 7 月 31 日更新:也许在使用 Angular 的 Spring 中,每个请求都不需要授权 header ?我的仓库在这里:Playground for Spring and Angular (AngularJS branch) , 每个创建的用户的密码都是 test

最佳答案

如果您使用的是基本身份验证,那么在 spring 中配置表单登录也没有多大意义。使用基本身份验证时,需要为每个需要在服务器上进行身份验证的请求提供 http Authorization header 。如果 protected 资源不存在授权 header ,Spring 将返回 401 响应。

你的设置在我看来是正确的(是的,“/jobs/**”匹配“/jobs”),但我猜你验证安全约束是否有效的实验失败了,因为服务器还设置了一个 jsessionid cookie可用于对您进行身份验证。因此,如果您请求没有授权 header 但具有有效 jsessionid cookie 的 protected 资源,那么服务器仍然可以对您进行身份验证。

您可以通过将 session 创建策略设置为无状态来告诉 spring-security 不要与 http session 交互。

尝试以下安全配置:

protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.authorizeRequests()
.antMatchers("/jobs/**").authenticated()
.antMatchers("/interviews/**").authenticated()
.anyRequest().permitAll()
.and()
.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and();
}

关于javascript - 当使用 AngularJS 登录后授权 header 不存在时,Spring Security 不会抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38551537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com