Spring Security を使用して、Spring Data REST Web アプリケーションを AngularJS で保護しています。
私の SecurityConfig は次のように宣言されています。
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.httpBasic().and()
.authorizeRequests()
// public ressources
.antMatchers("/index.html", "/templates/public/**", "/js/**", "/").permitAll()
.antMatchers(HttpMethod.GET, "/api/security/user").permitAll()
.antMatchers("/api/**").hasAnyRole("ADMIN", "NORMALUSER")
.anyRequest().authenticated()
.and().exceptionHandling().authenticationEntryPoint(basicAuthenticationEntryPointHandler)
.and().logout().logoutUrl("/logout").logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler()).deleteCookies("JSESSIONID").permitAll().and()
.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
}
私は通常、目標を達成するためにこのリンクをたどりました。
ここで、初めてログインすると、angular-request for return undefined$cookies.get("XSRF-TOKEN")
が返され、データベースへのすべてのリクエストがブロックされません。
しかし、ログアウトして再度ログインすると、Cookie が返され、すべてのデータベース リクエストが許可されます。
そして、これは 2 回目のログインごとにのみ発生するため、次のようになります。
未定義
クッキー
未定義
クッキー
未定義
...
だから今、私の構造に深く入り込まずに私を助けてくれる人がいることを願っていますが、それが必要な場合はそうします.
前もって感謝します。
プロセスに関連して: 私はトークンを CokieCsrfTokenRepository().loadToken() に記録しており、すべてのトークンが表示されています..
編集 2:ログインごとに呼び出す My Angular Service:
function authenticationService($rootScope, $http, $location, $filter, $cookies){
function authenticate(credentials, callback) {
var headers = credentials ? {authorization : "Basic "
+ btoa(credentials.username + ":" + credentials.password)
} : {};
$http.get('api/security/user', {headers : headers}).success(function(data, status, get, header) {
if (data.name) {
$rootScope.authenticated = true;
$rootScope.session = data;
console.log($cookies.get("XSRF-TOKEN")) // -> returns every second login cookie
} else {
$rootScope.authenticated = false;
$rootScope.session = null;
}
console.log($rootScope.session)
callback && callback();
}).error(function() {
$rootScope.authenticated = false;
callback && callback();
});
}
return {
authenticate: function(credentials){
authenticate(credentials, function() {
if ($rootScope.authenticated == true) {
$rootScope.authenticationError = false;
if ($rootScope.session.principal.admin == true){
$location.path("/admin/manage");
} else{
$location.path("/user");
}
} else {
$rootScope.authenticationError = true;
$location.path("/login");
}
});
},
// called by refreshing browser
checkLoggedIn: function(){
authenticate();
},
logout: function(){
$http.post('/logout', {})["finally"](function() {
$rootScope.authenticated = false;
$rootScope.session = null;
$location.path("/login");
});
}
};
}
編集 3: Cookie が定義されていない場合、このリンクのメソッド loadToken() は、ログアウトしてブラウザーを更新した後 (最初のログイン) にのみ呼び出されることを述べました。次に、トークンが表示され、再びログインします。しかし、毎秒試した後でも、うまく機能します..
編集 4:最初の禁止された POST 要求 (Edit3 では /logout) の後、トークンがテンプレートに到着することを認識しませんでした。ブラウザを更新すると、リクエストごとに Cookie が送信されるようになるため、すべてのリクエストが許可されます。しかし、これを修正する方法は?