gpt4 book ai didi

java - 如何在 Spring Security 后端从 Angular 应用程序正确验证用户身份

转载 作者:行者123 更新时间:2023-12-01 22:54:32 25 4
gpt4 key购买 nike

我正在尝试在由 Spring Security 保护的 Spring Boot 2.1 后端验证我的 Angular 8 应用程序。根据 Active Directory 检查用户请求。如果用户可以通过身份验证,我想返回一个包含用户名和权限的 JSON 响应。另外我想设置一个cookie。我设法解决了 cors 问题,并且能够使用 Postman 获得正确的响应。但我无法在我的 Angular 应用程序中获得正确的信息。

Spring 启动

LoginController.java

@RestController
@CrossOrigin(origins = "http://localhost:4200", allowCredentials = "true")
@RequestMapping("/login")
public class LoginController {
SecurityContext context;
Authentication authentication;
Collection<GrantedAuthority> grantedAuthorities;
String cips_authorities = "";

@GetMapping(value = "/loginPage")
public String loginPage() {
String loginForm = "<html >\n " +
"<head></head>\n" +
"<body>\n" +
" <h1>Login</h1>\n" +
" <form name='f' action=\"/login/loginPage\" method='post'>\n" + // @{/login}
" <table>\n" +
" <tr>\n" +
" <td>User:</td>\n" +
" <td><input type='text' name='username' id='username' value=''></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td>Password:</td>\n" +
" <td><input type='password' name='password' id='password' /></td>\n" +
" </tr>\n" +
" <tr>\n" +
" <td><input name=\"submit\" type=\"submit\" value=\"submit\" /></td>\n" +
" </tr>\n" +
" </table>\n" +
" </form>\n" +
"</body>\n" +
"</html>";

return loginForm;
}
@GetMapping(value = "/successful")
public String successful(HttpServletResponse response) {

response.setHeader("Access-Control-Allow-Origin", "*");
context = SecurityContextHolder.getContext();
authentication = context.getAuthentication();

grantedAuthorities = (Collection<GrantedAuthority>) authentication.getAuthorities();
cips_authorities = "";
if (grantedAuthorities.toString().contains("CIPS_INVOICE")) {
cips_authorities += ", \"CIPS_INVOICE\"";
}
if (grantedAuthorities.toString().contains("CIPS_STATS")) {
cips_authorities += ", \"CIPS_STATS\"";
}
if (cips_authorities.length() > 2) {
cips_authorities = "[" + cips_authorities.substring(2) + "]";
}

String userInformation = "{" +
"\"userName\":\"" + authentication.getName() + "\"," +
"\"authorities\":" + cips_authorities + "," +
"\"authenticated\":\"" + authentication.isAuthenticated() + "\"" +
"}";

return userInformation;
}

@GetMapping(value = "/logout")
public String logout() {
context = SecurityContextHolder.getContext();

String error = "{" +
"\"userName\":\"" + authentication.getName() + "\"," +
"\"authenticated\":\"" + authentication.isAuthenticated() + "\"" +
"}";

return error;
}

@GetMapping(value = "/active")
public String active() {
context = SecurityContextHolder.getContext();
authentication = context.getAuthentication();

String userInformation = "{" +
"userName:" + authentication.getName() + "," +
"authenticated:" + authentication.isAuthenticated() +
"}";

return userInformation;
}

@GetMapping(value = "/loggedOut")
public String logedout() {
context = SecurityContextHolder.getContext();
authentication = context.getAuthentication();

String userInformation = "{" +
"\"session\":\"logged out\"" +
"}";

return userInformation;
}

@GetMapping(value = "/failed")
public String failed() {
context = SecurityContextHolder.getContext();
authentication = context.getAuthentication();

String error = "{" +
"\"userName\":\"" + authentication.getName() + "\"," +
"\"authenticated\":\"" + authentication.isAuthenticated() + "\"" +
"}";

return error;
}

@GetMapping(value = "/invalidSession")
public String invalidSession() {
String error = "{" +
"\"session\":\"invalid\"" +
"}";
return error;
}
}

BasicConfiguration.java

@Configuration
@EnableWebSecurity
//@EnableGlobalMethodSecurity(prePostEnabled = true)
public class BasicConfiguration extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf()
.disable()
.authorizeRequests()
.antMatchers("/login/**")
.permitAll()
.antMatchers("/error/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.defaultSuccessUrl("/login/successful", true)
.and()
.formLogin()
.loginPage("/login/loginPage")
.permitAll()
.and()
.formLogin()
.failureUrl("/login/failed")
.and()
.logout()
.and()
.httpBasic()
.and()
.x509()
.disable();

http.logout()
.logoutUrl("/login/logout")
.logoutSuccessUrl("/login/loggedOut")
.clearAuthentication(true)
.deleteCookies("JSESSIONID")
.invalidateHttpSession(true)
.permitAll()
.invalidateHttpSession(true);


http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED);
http.sessionManagement().maximumSessions(1);
http.sessionManagement().invalidSessionUrl("/login/invalidSession");
http.sessionManagement().sessionFixation().newSession();
}

@Bean
public CorsConfigurationSource corsConfigurationSource () {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOrigins(Arrays.asList("*"));
corsConfiguration.setAllowedMethods(Arrays.asList("GET", "POST"));
corsConfiguration.setAllowedHeaders(Arrays.asList("authorization", "content-type", "x-auth- token"));

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return source;
}

}

postman 结果

Request: 
Headers:
Content-Type: application/x-www-form-urlencoded
Body:
username: <my-username>
password: <my-password>

Response:
Headers:
Date: Fri, 18 Oct 2019 06:44:50 GMT
Access-Control-Allow-Origin: *
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Typ: text/plain;charset=utf-8"
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block"
X-Frame-Options: DENY
Content-Lenght: 91
Cookies:
Name: JSESSIONID
Value: node01hidiu16ks9zn1owypmdrimsxw3.node0
Body:
{"userName":"<my-username>","authorities":["CIPS_INVOICE", "CIPS_STATS"],"authenticated":"true"}

角度结果

Code for the request: 
const formdata = new FormData();
formdata.append('username', username);
formdata.append('password', password);

this.http.post(`${environment.apiUrl}/login/loginPage`, formdata, {responseType: 'text'})
.subscribe(res => {
console.log('response', res);
});

Response:
response {"userName":"anonymousUser","authorities":,"authenticated":"true"}

我的问题:为什么当我从 Angular 应用程序发送请求时无法从 AD 获取信息,尽管通过 Postman 发送请求可以获取这些信息?我该如何改变这一点?

最佳答案

您需要明确告诉 Angular 以获得完整响应,而不仅仅是正文。

默认情况下,Angular httpClient 仅返回正文。为了获得完整的响应,您需要在 httpOptions 中添加
observe: 'response' 类似这样的

var headers = new Headers();
headers.append('Content-Type', 'application/json');
let httpOptions = new RequestOptions({ headers: headers, withCredentials: true, observe: 'response' });

return this.http.post(url, data, httpOptions)
.subscribe(res => {
console.log('response', res);
});
});

有关更多详细信息,请参阅angular docs - reading full response

关于java - 如何在 Spring Security 后端从 Angular 应用程序正确验证用户身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58446062/

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