春季安全与AngularJS - 404注销 [英] Spring security with AngularJS - 404 on logout
问题描述
我和教程,介绍了如何使用Spring开机,春季安全和AngularJS写简单的单页应用工作:的 https://spring.io/guides/tutorials/spring-security-and-angular-js/
我不能注销当前登录的用户 - 当我执行POST请求到/注销,我得到404未找到 - 从屏幕谷歌浏览器的调试器:
为什么要?我执行POST。为什么/登录?注销,而不是/注销?下面是当用户点击退出按钮时调用code:
$ scope.logout =功能(){
$ http.post('注销',{})。成功(函数(){
$ rootScope.authenticated = FALSE;
$ location.path(/);
})错误(功能(数据){
CONSOLE.LOG(注销失败)
$ rootScope.authenticated = FALSE;
});
}
春季code:
@SpringBootApplication
@RestController
公共类的UIApplication { @RequestMapping(/用户)
公共主要用户(主要用户){
返回用户;
} @RequestMapping(/资源)
公共地图<弦乐,对象>家(){
地图<弦乐,对象>模型=新的HashMap<弦乐,对象>();
model.put(ID,UUID.randomUUID()的toString());
model.put(内容,Hello World的);
回归模型;
} 公共静态无效的主要(字串[] args){
SpringApplication.run(UiApplication.class,参数);
} @组态
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
保护静态类SecurityConfiguration扩展WebSecurityConfigurerAdapter {
@覆盖
保护无效配置(HttpSecurity HTTP)抛出异常{
http.httpBasic()和()。authorizeRequests()
.antMatchers(/ index.html中,/home.html,/login.html,/)。permitAll()。anyRequest()
.authenticated()和()。CSRF()
.csrfTokenRepository(csrfTokenRepository())和()
.addFilterAfter(csrfHeaderFilter(),CsrfFilter.class);
} 私人过滤csrfHeaderFilter(){
返回新OncePerRequestFilter(){
@覆盖
保护无效doFilterInternal(HttpServletRequest的请求,
HttpServletResponse的响应,FilterChain filterChain)
抛出了ServletException,IOException异常{
CsrfToken CSRF =(CsrfToken)request.getAttribute(CsrfToken.class
.getName());
如果(CSRF!= NULL){
饼干饼干= WebUtils.getCookie(请求,XSRF-TOKEN);
字符串标记= csrf.getToken();
如果(饼干== NULL ||令牌!= NULL
&功放;&安培; !token.equals(cookie.getValue())){
饼干=新的Cookie(XSRF-TOKEN令牌);
cookie.setPath(/);
response.addCookie(饼干);
}
}
filterChain.doFilter(请求响应);
}
};
} 私人CsrfTokenRepository csrfTokenRepository(){
HttpSessionCsrfTokenRepository库=新HttpSessionCsrfTokenRepository();
repository.setHeaderName(X-XSRF-TOKEN);
返回库;
}
}}
整个AngularJS code:
angular.module('你好',['ngRoute'])。配置(函数($ routeProvider,$ httpProvider){ $ routeProvider
。当('/',{templateUrl:home.html做为',控制器:'家'})
。当('/登录',{templateUrl:'的login.html',控制器:'导航'})
。除此以外('/'); $ httpProvider.defaults.headers.common ['X-要求-随着'] ='XMLHtt prequest';})。控制器('导航', 功能($ rootScope,$范围,$ HTTP,$位置$路线){ $ scope.tab =功能(路线){
返回$ route.current&放大器;&安培;路线=== $ route.current.controller;
}; VAR身份验证=功能(凭证,回调){ VAR标题=凭据? {
授权:基本
+ BTOA(credentials.username +:
+ credentials.password)
}:{}; $ http.get('用户',{
标题:标题
})。成功(功能(数据){
如果(data.name){
$ rootScope.authenticated =真;
}其他{
$ rootScope.authenticated = FALSE;
}
回调和放大器;&安培;回调($ rootScope.authenticated);
})错误(函数(){
$ rootScope.authenticated = FALSE;
回调和放大器;&安培;回调(假);
}); } 认证();
$ scope.credentials = {};
$ scope.login =功能(){
验证($ scope.credentials,功能(认证){
如果(认证){
的console.log(登录成功)
$ location.path(/);
$ scope.error = FALSE;
$ rootScope.authenticated =真;
}其他{
的console.log(登录失败)
$ location.path(/登录);
$ scope.error = TRUE;
$ rootScope.authenticated = FALSE;
}
})
}; $ scope.logout =功能(){
$ http.post('注销',{})。成功(函数(){
$ rootScope.authenticated = FALSE;
$ location.path(/);
})错误(功能(数据){
CONSOLE.LOG(注销失败)
$ rootScope.authenticated = FALSE;
});
} })。控制器('家',函数($范围,$ HTTP){
$ http.get('/资源/')。成功(功能(数据){
$ scope.greeting =数据; })});
我是新来的春天。下面是从教程整个code - 不工作过:
https://github.com/dsyer/spring-security-angular/tree /主/单
其实你需要的就是添加注销成功处理程序是什么
@Component
公共类LogoutSuccess实现LogoutSuccessHandler {@覆盖
公共无效onLogoutSuccess(HttpServletRequest的HttpServletRequest的,HttpServletResponse的HttpServletResponse的,验证认证)
抛出IOException异常,ServletException异常{
如果(认证= NULL&放大器;!&安培;!authentication.getDetails()= NULL){
尝试{
httpServletRequest.getSession()无效()。
//你可以在这里添加更多codeS当用户成功登录
//出来,
//如更新为最后一个活动数据库。
}赶上(例外五){
e.printStackTrace();
E = NULL;
}
} httpServletResponse.setStatus(HttpServletResponse.SC_OK);}}
和添加成功处理您的安全配置
<$p$p><$c$c>http.authorizeRequests().anyRequest().authenticated().and().logout().logoutSuccessHandler(logoutSuccess).deleteCookies(\"JSESSIONID\").invalidateHttpSession(false).permitAll();I'm working with tutorial that describes how to write simple single-page app using Spring Boot, Spring Security and AngularJS: https://spring.io/guides/tutorials/spring-security-and-angular-js/
I cannot logout currently logged user - when I perform POST request to "/logout", I get "404 not found" - screen from Google Chrome debugger:
Why GET? I performed POST. Why "/login?logout", not "/logout"? Here is the code that is invoked when user clicks logout button:
$scope.logout = function() {
$http.post('logout', {}).success(function() {
$rootScope.authenticated = false;
$location.path("/");
}).error(function(data) {
console.log("Logout failed")
$rootScope.authenticated = false;
});
}
Spring code:
@SpringBootApplication
@RestController
public class UiApplication {
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
@RequestMapping("/resource")
public Map<String, Object> home() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("id", UUID.randomUUID().toString());
model.put("content", "Hello World");
return model;
}
public static void main(String[] args) {
SpringApplication.run(UiApplication.class, args);
}
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().and().authorizeRequests()
.antMatchers("/index.html", "/home.html", "/login.html", "/").permitAll().anyRequest()
.authenticated().and().csrf()
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null
&& !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
};
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
}
}
Whole AngularJS code:
angular.module('hello', [ 'ngRoute' ]).config(function($routeProvider, $httpProvider) {
$routeProvider
.when('/', {templateUrl : 'home.html', controller : 'home' })
.when('/login', { templateUrl : 'login.html', controller : 'navigation' })
.otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}).controller('navigation',
function($rootScope, $scope, $http, $location, $route) {
$scope.tab = function(route) {
return $route.current && route === $route.current.controller;
};
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).success(function(data) {
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback($rootScope.authenticated);
}).error(function() {
$rootScope.authenticated = false;
callback && callback(false);
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function(authenticated) {
if (authenticated) {
console.log("Login succeeded")
$location.path("/");
$scope.error = false;
$rootScope.authenticated = true;
} else {
console.log("Login failed")
$location.path("/login");
$scope.error = true;
$rootScope.authenticated = false;
}
})
};
$scope.logout = function() {
$http.post('logout', {}).success(function() {
$rootScope.authenticated = false;
$location.path("/");
}).error(function(data) {
console.log("Logout failed")
$rootScope.authenticated = false;
});
}
}).controller('home', function($scope, $http) {
$http.get('/resource/').success(function(data) {
$scope.greeting = data; }) });
I'm new to Spring. Here is the whole code from tutorial - doesn't work too: https://github.com/dsyer/spring-security-angular/tree/master/single
In fact what you need is just to add a logout success handler
@Component
public class LogoutSuccess implements LogoutSuccessHandler {
@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication)
throws IOException, ServletException {
if (authentication != null && authentication.getDetails() != null) {
try {
httpServletRequest.getSession().invalidate();
// you can add more codes here when the user successfully logs
// out,
// such as updating the database for last active.
} catch (Exception e) {
e.printStackTrace();
e = null;
}
}
httpServletResponse.setStatus(HttpServletResponse.SC_OK);
}
}
and add a success handler to your security config
http.authorizeRequests().anyRequest().authenticated().and().logout().logoutSuccessHandler(logoutSuccess).deleteCookies("JSESSIONID").invalidateHttpSession(false).permitAll();
这篇关于春季安全与AngularJS - 404注销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!