简体   繁体   中英

Spring 4 security login users-by-username-query is always login error

security-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.2.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">



    <security:authentication-manager>
        <security:authentication-provider>
            <security:jdbc-user-service
                data-source-ref="dataSource"
                users-by-username-query="select username, password, enabled from users where username=?"
                authorities-by-username-query="select username, authority  from authorities where username=?" />
            <security:password-encoder ref="passwordEncoder"></security:password-encoder>

        </security:authentication-provider>

    </security:authentication-manager>
    <security:http auto-config="true" create-session="always"
        use-expressions="true">

        <security:csrf disabled="true" />


        <security:intercept-url pattern="/" access="permitAll" />
        <security:intercept-url pattern="/home" access="permitAll" />
        <security:intercept-url pattern="/admin/**"
            access='hasRole("ROLE_ADMIN")' />

        <security:form-login login-page="/login"
            authentication-failure-url="/login?error=1" default-target-url="/" />


        <security:headers disabled="true"></security:headers>
    </security:http>
    <bean
        class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder"
        id="passwordEncoder">
    </bean>
</beans>

login Controller

package my.custom.project.controller;

import java.util.List;
import java.util.Locale;

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

import my.custom.project.model.User;
import my.custom.project.service.UserService;

@Controller
public class LoginController {


    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String Login(@RequestParam(value="error", required=false) String error, 
            @RequestParam(value="logout", required=false) String logout, Model model){

        if (error!=null){
            model.addAttribute("errorMsg","Invalid username and password");
        }
        if(logout!=null){
            model.addAttribute("logoutMsg", "You have been logged out successfully");
        }


        return "login";
    }

}

login.jsp

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<main role="main" style="margin-top:30px;" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<div class="container-wrapper">
    <div class="container">
        <h2>Login with username and password</h2>
        <c:if test="${not empty errorMsg}">
            <div style="color: #ff0000">
                <h3>${errorMsg}</h3>
            </div>
        </c:if>
        <c:if test="${not empty logoutMsg}">
            <div style="color: #0000ff">
                <h3>${logoutMsg}</h3>
            </div>
        </c:if>


        <form action="<c:url value="/login"/>" method="post">
            <div class="form-group">
                <label for="username">Username:</label> <input type="text"
                    class="form-control" id="uesrname" placeholder="Enter username"
                    name="username" style="width: 50%">
            </div>

            <div class="form-group">
                <label for="pwd">Password:</label> <input type="password"
                    class="form-control" id="passwd" placeholder="Enter password"
                    name="password" style="width: 50%">
            </div>

            <input type="hidden" name="${_csrf.parameterName}"
                value="${_csrf.token}" />


            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>
</div>
</main>

MySQL DB

enter image description here

And Result is... enter image description here

username, passworr is correct. but result is always failed. I can receive users's data in controller by userService. I guess useDao is correct working. Is problem at spring security security:jdbc-user-service ?

How to resolve this problem?

Spring does provide Utility class for BCryptPasswordEncoder encoding

Something like this

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class PasswordEncoderGenerator {

  public static void main(String[] args) {

    String password = "123456";
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String hashedPassword = passwordEncoder.encode(password);

    System.out.println(hashedPassword);

  }
}

You can use this to generate passowrd for yout users eg for admin.

Take hashedPassword and replace it in password column in Users table in MySQL and try login.

Refer this for more detail

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM