当前位置: 首页 > 知识库问答 >
问题:

在spring boot starter安全性中使用自定义登录页面成功登录,未进入下一页

龚玄天
2023-03-14

我一直在研究春靴。当使用spring-boot-starter-security为todo应用程序时,我尝试使用自定义的用户id和密码以及自定义的登录页面进行登录,当我尝试登录时,它并没有将我带到下一页。注意:用户名是下一页的必选参数。

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login").permitAll()
                .antMatchers("/", "/*Todo*/**").access("hasRole('USER')").and()
                .formLogin().loginPage("/login").permitAll();
    }
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login").permitAll()
                .antMatchers("/listTodo").hasAnyRole("USER","ADMIN")
                .anyRequest().authenticated()
                .and().formLogin().loginPage("/login").permitAll().and()
                .logout().permitAll();
}
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("Sudhakar").password("qwe123").roles("USER","ADMIN");
    }
}

I would need to login with user name and get the todo details of the user who logged in. But I am not able to get to next page, after trying many times I am getting below error

java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null"

Below is my controller
package com.example.SpringLogin.Controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.example.SpringLogin.service.loginService;

@Controller
@SessionAttributes("name")
public class LoginController {
    @Autowired
    loginService service;

    @RequestMapping(value="/login",method = RequestMethod.POST)
    public String loginMessage(ModelMap model,@RequestParam String name,@RequestParam String password) {
        boolean isValidUser=service.validateUser(name, password);

        if(!isValidUser) {
            model.put("message", "Invalid Credentials");
            return"Room";
        }
        model.put("name", name);
        model.put("password",password);

        return "redirect:/todoList";
    }
    @RequestMapping(value="/login",method = RequestMethod.GET)
    public String roomLogin(ModelMap model, String error) {
        //model.put("name", name);
        if(error!=null) {
            model.addAttribute("errorMsg","UserName or Password is invalid");
        }
        return "Room";
    }
    /*@RequestMapping(value="/login",method = RequestMethod.GET)
    public String showLogin(ModelMap model) {
        //model.put("name", name);
        return "Welcome";
    }*/
    @RequestMapping(value = "/welcome")
    public String showWelcome(ModelMap model) {
        return "login";
    }
}

My login page

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="contextPath" value=""/>
<!DOCTYPE html>
<html>
<head>

<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
    rel="stylesheet">
<title>Todo Application</title>
</head>
<body>
    <div class="container">
        <font color="red">${message}</font>
        <form:form method="post" action="/login">
            <fieldset class="form-group">
                Name : <input type="text" name="username" class="form-control" placeholder="Username"
                   autofocus="true"/>
                Password: <input type="password" name="password"
                    class="form-control" placeholder="Password" />
            </fieldset>
            <button type="submit" class="btn btn-success">Submit</button>
        </form:form>
    </div>
<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
    <script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>

After successful login it should go to below page

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<c:set var="contextPath" value=""/>
<!DOCTYPE html>
<html>
<head>

<link href="webjars/bootstrap/3.3.6/css/bootstrap.min.css"
    rel="stylesheet">
<title>Todo Application</title>
</head>
<body>
    <div class="container">

    <table class="table table-striped">
        <H1>Name : ${pageContext.request.userPrincipal.name}</H1>

        <thead>
            <tr>
                <th>Id</th>
                <th>Course</th>
                <th>End Date</th>
                <th>Is it Done</th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${todo}" var="item">
                <tr>
                    <td>${item.id}</td>
                    <td>${item.course}</td>
                    <td><fmt:formatDate value="${item.date}" pattern="MM/dd/yyyy" /></td>
                    <td>${item.isdone?'Yes':'No'}</td>
                    <td><a type="button" class="btn btn-success"
                        href="/update-Todo?id=${item.id}">Update</a></td>
                    <td><a type="button" class="btn btn-warning"
                        href="/delete-Todo?id=${item.id}">Delete</a></td>
                </tr>
            </c:forEach>
        </tbody>
    </table>

    <div>
        <a type="button" href="/add-Todo" class="btn btn-success">Add a
            Todo</a>
    </div>
</div>

<script src="webjars/jquery/1.9.1/jquery.min.js"></script>
    <script src="webjars/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</body>
</html>

Service class

package com.example.SpringLogin.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.stereotype.Service;

import com.example.SpringLogin.model.todoList;

@Service
public class TodoService {

    public static List<todoList> todos=new ArrayList<todoList>();
    public static int todoCount=5;

    static {
        todos.add(new todoList(1, "Sudhakar", "Study history", new Date(), false));
        todos.add(new todoList(2,"Sudhakar","Study geography",new Date(),false));
        todos.add(new todoList(3,"Sudhakar","Study GK",new Date(),false));
        todos.add(new todoList(4,"Mani","Study Java",new Date(),false));
        todos.add(new todoList(5,"Mani","Study script",new Date(),false));
    }

    public List<todoList> retrievetodos(String name){
        List<todoList> retrieved=new ArrayList<todoList>();
        for (todoList todo : todos) {

            if(todo.getName().equalsIgnoreCase(name)) {
                retrieved.add(todo);
            }
        }
        return retrieved;
    }

    public void addTodo(String name,String Course,Date date,boolean isDone) {
        todos.add(new todoList(++todoCount,name,Course,date,isDone));
    }

    public todoList retrieveTodo(int id){

        for (todoList todo : todos) {
            if(todo.getId()==id) {
                return todo;
            }
        }
        return null;        
    }

    public List<todoList> UpdateTodo(todoList todo){
        /*for (todoList td : todos) {
            if(td.getId()==todo.getId()) {
                td.setCourse(todo.getCourse());
                td.setDate(todo.getDate());
            }
        }*/

        todos.remove(todo);
        todos.add(todo);
        return todos;
    }
     //it will delete the todo
    public void deleteTodo(int id) {
        Iterator<todoList> it = todos.iterator();
        while(it.hasNext()){
            todoList td=it.next();
            if(td.getId()==id) {
                it.remove();
            }
        }
    }
}

共有1个答案

曾山
2023-03-14

尝试添加LoginProcessURLDefaultSuccessURL。类似于这样:

.formLogin()
.loginPage("/login")
.loginProcessingUrl("/do_login")
.defaultSuccessUrl("/index")

本例中的索引是您成功登录后要访问的页面。

 类似资料:
  • 而且,再一次,即使键入正确的凭据,正如我在“userDetailsService”方法中指定的那样,我也无法登录,但这次我终于可以在控制台上看到错误消息: 显然我走了,但没有离开这个地方,因为现在我不知道我的代码有什么问题...

  • 我遵循了spring boot安全教程,但最终结果有一个问题,即在成功登录后,浏览器重定向到。 我什至克隆了教程中引用的代码,认为我输入错误的内容,或者忘记添加组件或其他内容。不,同样的问题也存在。 在Stackoverflow上搜索时,我发现您需要在< code > WebSecurityConfigurerAdapter 的< code>configure方法中定义默认的成功URL,如下所示:

  • 我正在为Spring Security实现一个自定义的AngularJS登录页面,但在身份验证方面存在问题。 遵循本教程/示例,他们的示例在本地工作得很好。 值得注意的变化(也很可能是我的问题的根源): > 文件结构更改 使用严格的Angular(没有jQuery)--这将导致发出POST请求所需的不同函数 用bower代替wro4j 角代码样式/范围 许多相关的Spring Security问题

  • 请参考一些wordpress post登录插件。我有3页的网站主页,关于正常工作和工作安全,我想显示工作安全页面,如果用户登录有电子邮件/只是虚拟id,我可以生成。找不到此登录模块的插件。带有自定义页面的自定义菜单 使用这个脚本,我可以创建菜单,但不能重定向单独的页面 函数my_wp_nav_menu_args($args=''){ 如果(用户是否已登录){ }否则{ } } 添加过滤器(“wp\

  • 我在我的JSF应用程序中使用容器管理的安全性,因此我有一个低于默认设置的登录页面。 现在在登录页面中,我想在登录按钮旁边添加一个按钮,以允许用户注册。 但我该如何将其转发到我的登记簿。我的注册按钮的xhtml页面?我用以下代码进行了尝试: 我也尝试将表单更改为h: form,以便我可以使用p:命令按钮,但正如我注意到的,我的登录页面不工作,当我单击提交按钮时什么也没有发生。 如何实现我想做的事?

  • 通过设置安全码,从而达到隐藏登录页的效果,保证页面的私有性。 /app/Application/Admin/Conf/config.php return array( 'LOGIN_MAX_FAILD' => 5, 'BAN_LOGIN_TIME' => 30, //登录失败5次之后需等待30分钟才可再次登录 'ADMIN_PANEL_SECURITY_CODE' => '