【发布时间】:2016-01-11 17:09:46
【问题描述】:
我正在努力使用 Spring Security 创建一个小型身份验证系统,但我还没有运气。
我想要的是一个登录表单,它通过 AngularJS 进入数据库并使用提供的数据进行搜索。为了使它工作,我尝试使用内存数据库。
这是我使用的代码:
@RestController
@RequestMapping("/authentication")
public class AuthenticationController {
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
@Configuration
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/index.html", "/home.html", "/login.html", "/lib/**", "/app/**", "/css/**", "/js/**").permitAll().anyRequest()
.authenticated();
http.formLogin().loginPage("/login.html").defaultSuccessUrl("/index.html")
.failureUrl("/login?error").permitAll();
// Logout
http.logout().logoutUrl("/logout").logoutSuccessUrl("/login?logout")
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
// Authorization
auth.inMemoryAuthentication().withUser("user").password("p1")
.roles("USER");
auth.inMemoryAuthentication().withUser("root").password("p2")
.roles("USER", "ADMIN");
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
}
}
这是来自 Angular 的身份验证功能:
function($rootScope, $scope, $http, $location) {
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('authentication/user', {
headers : headers
}).success(function(data) {
console.log(data.name);
if (data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback();
}).error(function() {
$rootScope.authenticated = false;
callback && callback();
});
}
authenticate();
$scope.credentials = {};
$scope.login = function() {
authenticate($scope.credentials, function() {
if ($rootScope.authenticated) {
$location.path("/index.html");
$scope.error = false;
} else {
//$location.path("/login");
$scope.error = true;
}
});
};
});
您知道为什么这不起作用吗?我从一些非常相似的教程中获取了提供的代码。在此之前,我尝试了一种稍微不同的方法,它使用了httpBasic,但仍然没有得到想要的结果。
有什么建议吗?谢谢!
【问题讨论】:
-
没有得到想要的结果。 ...但是你期望什么,你有什么?
-
当我输入
user和p1时,我希望被重定向到index.html。我对这些期望有错吗?据我了解,当您通过身份验证时,它应该在这些标头中添加一些内容。这是我第一次使用 spring,我阅读了一些关于 Spring Security 身份验证方式的内容,但仍然很难弄清楚如何去做。
标签: java angularjs spring rest spring-security