gpt4 book ai didi

javascript - 使用 AngularJS $http.post 登录到 Spring Boot

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

我有一个 spring boot 应用程序,想通过我的 angularJS 服务登录它。我确实通过将 cookie 保存在我的浏览器中的 postman 登录,但我想使用我的服务再次登录。由于我的 cookie,我可以在我的 spring boot 应用程序中调用任何 Controller (它们都需要身份验证)。但是所有登录请求都失败并出现错误“未授权”。完整的浏览器控制台输出 -发布http://localhost:3344/bl/login 401(未授权)

spring 的安全配置(我扩展了 WebSecurityConfigurerAdapter):

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication()
.dataSource(dataSource)
.passwordEncoder(passwordEncoder())
.usersByUsernameQuery(USERS_BY_USERNAME_QUERY)
.authoritiesByUsernameQuery(AUTHORITIES_BY_USERNAME_QUERY);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/").authenticated()
.and()
.formLogin()
.loginProcessingUrl("/bl/login")
.usernameParameter("user")
.passwordParameter("pass")
.successHandler(authenticationSuccessHandler)
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
.and()
.logout()
.logoutUrl("/logout")
.invalidateHttpSession(true);
}

我的 Angular 服务非常简单:

loginModule.factory('loginService', function($http) {
return {
login: function(username, password) {
$http.post('/bl/login', {user: 'admin', pass: 'admin'}).then(
function(response) {
window.alert('success')
},
function(response){
window.alert('fail')
});
}
};
});

我还创建了一个 Controller 作为“模拟”登录服务来测试我的 Angular 代码:

@RequestMapping(value ="/bl/login2", produces="application/json")
JSONResponse login(@RequestBody LoginCreds credentials) {

return new JSONResponse("logged in " + credentials.getUser());
}

这个 Controller 可以工作,我可以看到我的登录名和密码已正确传递,并且我得到了对我的 Angular 服务的响应。LoginCreds 包含 2 个字符串 'user' 和 'pass'。JSONResponse 包含单个字符串。

最佳答案

已解决,问题是在我的 spring 配置中我有“formLogin()”,这意味着我必须将请求中的内容类型 header 从 Angular 服务更改为“application/x-www-form-urlencoded”。并相应地序列化数据。 This link explains it with examples.

我的最终结果是这样的:

     var req = {
method: 'POST',
url: 'bl/login',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: $.param({ user: username, pass: password }),
};

$http(req).then(
function(response) {
window.alert('success')
},
function(response){
window.alert('fail')
});
}

由于angular默认将数据序列化为JSON,所以我们需要使用$.param()函数进行序列化。

关于javascript - 使用 AngularJS $http.post 登录到 Spring Boot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35141407/

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