简体   繁体   中英

Spring security login dynamically

I have a file bean:

<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
      http://www.springframework.org/schema/security
      http://www.springframework.org/schema/security/spring-security-3.1.xsd">

<http auto-config="true">
  <intercept-url pattern="/secured/*" access="ROLE_USER" />
    <form-login login-processing-url="/login" login-page="/loginPage"
        username-parameter="username" password-parameter="password"
        default-target-url="/secured/mypage" authentication-failure-url="/loginPage?auth=fail" />
    <logout logout-url="/logout" logout-success-url="/logoutPage" />        
</http>

<authentication-manager>
    <authentication-provider>
        <user-service>
            <user name="srccodes" password="password" authorities="ROLE_USER" />
        </user-service>
    </authentication-provider>
</authentication-manager>

I have a login page I check login password from extern database, the login is différent of "srccodes" password="password". How can I add user dynamycally and affect to him for example ROLE_USER ?

Check this example According to your example you store password and users details in xml! It will get user credintals from database tabke
1. you have to change setup of authentification manager

<authentication-manager>
  <authentication-provider>
    <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, role from user_roles where username =?  " />
  </authentication-provider>
</authentication-manager>

And setup connection to Database

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/test" />
    <property name="username" value="root" />
    <property name="password" value="password" />
</bean>
  1. if you want to create user you have to insert new record into

    users table and user_roles table

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