使用Spring Security登录HTML后重定向到主页

时间:2018-07-05 12:10:09

标签: javascript html spring-security

我正在尝试登录并将请求重定向到主页。在当前状态下,我可以成功登录,但可以查看空白页。我不想在spring / server端使用重定向策略。我的HTML登录页面如下:

<!DOCTYPE html>
<html>
<body>
<form action="/login.html" method="post">
    <input type="text" name="username" required>
    <input type="password" name="password" required>
    <input type="submit" value="Login" />
</form>
</body>
</html>

Spring安全配置:

http.authorizeRequests().antMatchers("/").permitAll().antMatchers("/**").hasAnyRole(new String[] { "ADMIN" }).and().formLogin().loginPage("/login.html").permitAll();

我想对HTML本身做一些修复,以便在成功时将请求重定向到首页,在失败时将请求重定向到登录页面本身。我该怎么做?我进行了很多搜索,但没有找到完美的解决方案,如果有人在此处发布答案会很好。

3 个答案:

答案 0 :(得分:1)

您可以实现一个端点来[检查用户是否已登录] [1]。

然后,您可以编写一个javascript函数来调用该端点,并在用户通过身份验证时重定向。从<body onload="yourfunction()">

调用函数

[1] How to check if a user is logged in with spring-security?

答案 1 :(得分:0)

您必须像这样指定自定义successHandler

http.formLogin()
  .loginPage("/login.html")
  .successHandler(myCustomSuccessHandler);

在您的successHandler中,您可以重定向到所需的任何URL。

请参见javadoc

答案 2 :(得分:0)

我能够使用angular js来完成这项工作:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="loginapp" ng-controller="loginctrl"> 
<form ng-submit="login();">
    <input type="text" ng-model="username" required>
    <input type="password" ng-model="password" required>
    <input type="submit" value="Login" />
</form>
</div>
<script>
var loginapp = angular.module('loginapp', []);
loginapp.controller('loginctrl', function($scope, $http, $window) {
    $scope.login = function(){$http({
        method: 'POST',
        url: '/login.html?username='+$scope.username+'&password='+$scope.password,
        headers: {'Content-Type': 'application/json'}
    }).then(function(response){$scope.user=response.data;$window.location.href= '/';});};
});
</script>
</body>
</html>