Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Authenticating users using the default login page


Spring makes it easy to quickly add a login page to your web application; just define some user credentials (usernames and passwords) in the security configuration class. To access any page, the user will have to go through Spring's default login page first.

How to do it…

In your security configuration class, add a configureUsers() method containing the hardcoded user credentials:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureUsers(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
.withUser("user1").password("pwd").roles("USER")
    .and()
.withUser("admin").password("admin_pwd").roles("USER", "ADMIN");

    }
}

How it works…

In configureUsers(), we told Spring to use the provided user credentials for user authentication. We assigned roles to each user. A role is an arbitrary String object. To use those roles...