0
我挣扎了几个小时,以创建一个使用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;
}
}
}
这是身份验证功能的角度:
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
但仍无法得到期望的结果。
有什么建议吗?谢谢!
*我没有得到期望的结果。* ......但你能指望什么?你有什么? – ben75
我希望当我输入'user'和'p1'重定向到'index.html'。这些期望我错了吗?根据我的理解,当您通过身份验证时,应该在这些标头中加入一些内容。这是我第一次使用Spring,我在Spring Security上阅读了一些关于认证方式的内容,但仍然很难弄清楚如何去做。 – tzortzik