看起来 dart 总是在浏览器中遵循这些重定向,我没有机会在第一个请求的标头中检索 cookie 或令牌。
因此,作为替代解决方案,我接下来尝试执行此操作:
在 Spring Security 中激活基本身份验证:
@Configuration
@EnableWebMvcSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/logout").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic()
.and()
.sessionManagement().sessionFixation().changeSessionId()
.and()
.csrf().disable();
}
...
}
在一个控制器中,我有这样的东西作为受保护的资源:
@RequestMapping(value = "login", method = RequestMethod.POST)
public String login() {
return RequestContextHolder.currentRequestAttributes().getSessionId();
}
通过这种方式,您可以获得会话 ID 作为常规结果。因此,我可以简单地从响应正文中获取 ID,并在我提供一次正确的基本身份验证凭据后使用它。
这只应在受信任的环境中或通过 https 使用,以使坏人更难嗅探凭据或会话。
所以基本上这就是我登录时所做的:
void login() {
Map<String, String> headers = {};
authorize(headers);
HttpRequest.request(LOGIN_URL, method: "POST", requestHeaders: headers)
.then((request) => processLogin(request))
.catchError((e) => processLoginError(e));
}
void processLogin(HttpRequest request) {
sessionController.sessionId=request.responseText;
mainApp.showHome();
}
void processLoginError(var e) {
print("total failure to login because of $e");
}
String authorization() {
String auth = window.btoa("$username:$password");
return "Basic $auth";
}
void authorize(Map<String, String> headers) {
headers.putIfAbsent("Authorization", () => authorization());
}
要发送请求,HeaderHttpSessionStrategy我可以这样做:
void updateUserData(){
_logger.info("Updating user data");
Map<String, String> headers = {"Accept": "application/json", 'x-auth-token':sessionId};
HttpRequest.request(USER_URL, method: "GET", requestHeaders: headers)
.then((request) => processUserData(request))
.catchError(ErrorHandler.handleHttpErrorGeneric);
}
你也可以让它与 cookie 一起工作,但我喜欢这样,HttpRequest.request()所以使用标题字段更容易。