Spring Security - 简单的用户注册(不是xml配置)

时间:2016-08-12 07:33:22

标签: java spring-mvc spring-security

我的项目“/ register”和“/ login”只有2页。 login.jsp页面来自默认的spring security login。 register.jsp是由我创建的。

我的春季安全配置:

package com.cihangirmercan.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth)
        throws Exception {

    auth.inMemoryAuthentication().withUser("cihangir").password("mercan")
            .roles("USER"); // the only user at the beginning
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/login", "/register").permitAll() // anonym can login or register
            .antMatchers("/").access("hasRole('USER')") // home page is not allowed if not user is logged in
            .and().formLogin();

    http.csrf().disable();
}
}

所以,在开始时,只有一个用户id:“cihangir”和pass:“mercan”可以通过过滤器和登录。我想要的是在用用户名和密码注册后,我希望这个新的注册有ROLE_USER,然后可以登录。

RegisterController:

package com.cihangirmercan.controller;

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;

@Controller
@SessionAttributes("registerWarning")
public class RegisterController {

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String showRegisterPage(ModelMap model) {
        return "register";
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String handleRegisterRequest(ModelMap model, 
                                        @RequestParam String username,
                                        @RequestParam String password) {

        // i want to give this username and password ROLE_USER
        // hence user can login with spring security

        // done
        return "redirect:/login";
    }
}

register.jsp:

<html>
<head>
<title>Register</title>
</head>
<body>
    <h1>Register</h1>
      <form action="/register" method="post" >
        <label>Username:</label>
        <input type="text" name="username" required><br><br>
        <label>Password:</label>
        <input type="password" name="password"><br><br>
        <input type="submit" value="Register">
      </form>
</body>
</html>

WelcomeController :(欢迎页面)

package com.cihangirmercan.controller;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class WelcomeController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String showWelcomePage(ModelMap model) {
        model.put("username", getLoggedInUserName());
        return "welcome";
    }

    private String getLoggedInUserName() {
        Object principal = SecurityContextHolder.getContext()
                .getAuthentication().getPrincipal();

        if (principal instanceof UserDetails)
            return ((UserDetails) principal).getUsername();

        return principal.toString();
    }
}

的welcome.jsp:

<html>
<head>
<title>Home</title>
</head>
<body>
    <h2>Home Page</h2>
    <br>
    <h4>${username} is at home.</h4>        
</body>
</html>

此外,我还有web.xml和dispatcher-servlet以及pom.xml。

3 个答案:

答案 0 :(得分:0)

查看此帖子:http://www.mkyong.com/tutorials/spring-security-tutorials/ 它包含有用的示例,包括基于注释的示例(您的案例),具有不同的技巧,如记住我,尝试限制等。

答案 1 :(得分:0)

您尚未正确配置登录信息

%

你已经在dispatch-xxx.xml中配置了视图解析器,就像这样

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.authorizeRequests()
            .antMatchers("/login", "/register").permitAll() // anonym can login or register
            .antMatchers("/").access("hasRole('USER')") // home page is not allowed if not user is logged in
            .and().formLogin().loginPage("/login")
            .and()
        .logout().logoutSuccessUrl("/register");

    http.csrf().disable();
}

答案 2 :(得分:0)

我使用jdbc身份验证解决了我的问题。 它动态更新用户和角色。

来源:https://dzone.com/articles/spring-security-4-authenticate-and-authorize-users