funky-nd
funky-nd

Reputation: 725

Spring Security - Simple User Registration (not xml configuration)

I have only 2 page in my project "/register" and "/login". login.jsp page is coming from default spring security login. register.jsp is created by me.

My spring security configuration:

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();
}
}

So, in the beginning, only one user id:"cihangir" and pass:"mercan" can pass the filter and login. What I want is after register with username and password, I want this new registration to has ROLE_USER and can login after that.

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: (welcome page)

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>

Besides, web.xml and dispatcher-servlet and pom.xml they are all I have.

Upvotes: 1

Views: 4438

Answers (2)

funky-nd
funky-nd

Reputation: 725

I solved my problem with using jdbc authentication. It dynamically updates users and roles.

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

Upvotes: 0

kuhajeyan
kuhajeyan

Reputation: 11017

you have not configured your login correctly

@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();
}

and you have configured the view resolver in your dispatch-xxx.xml, something like this

<bean
      class="org.springframework.web.servlet.view.InternalResourceViewResolver">
      <property name="prefix">
        <value>/WEB-INF/pages/</value>
      </property>
      <property name="suffix">
        <value>.jsp</value>
      </property>
    </bean>

Upvotes: 0

Related Questions