Comprehensive Guide to Spring Security: Setup, Authentication, Authorization, and Advanced Configurations

This article provides a detailed tutorial on Spring Security, covering its core concepts, project setup, authentication flow, custom user details service, password encoding, login handling, role-based access control, CSRF protection, and integration with Thymeleaf, complete with code examples.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Comprehensive Guide to Spring Security: Setup, Authentication, Authorization, and Advanced Configurations

Spring Security is a highly customizable security framework that leverages Spring IoC/DI and AOP to provide declarative security access control, reducing the need to write repetitive security code.

Core functions: authentication and authorization.

Spring Security Overview

Spring Security integrates with Spring Boot via the spring-boot-starter-security starter, enabling default protection of all requests and providing a built‑in login page.

Project Setup

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

After adding the starter, accessing http://localhost:8080/ redirects to the default login page where the username is user and the password is printed in the console at startup.

Custom Username and Password

Edit application.yml to define static users:

# Static user for internal network authentication
spring:
  security:
    user:
      name: test   # static username
      password: test   # static password

UserDetailsService Details

Implement UserDetailsService to load user data from a database:

@Component
public class UserSecurity implements UserDetailsService {
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userService.login(userName);
        if (null == user) {
            throw new UsernameNotFoundException("用户名错误");
        }
        return new org.springframework.security.core.userdetails.User(
                userName, user.getPassword(), AuthorityUtils.createAuthorityList()
        );
    }
}

PasswordEncoder Details

The PasswordEncoder interface handles password hashing and verification. Spring Security provides several implementations, and you can create a custom MD5 encoder:

/**
 * Credential matcher for authentication.
 */
public class MyMD5PasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            return toHexString(digest.digest(charSequence.toString().getBytes()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }
    }
    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(encode(charSequence));
    }
    private String toHexString(byte[] tmp) {
        StringBuilder builder = new StringBuilder();
        for (byte b : tmp) {
            String s = Integer.toHexString(b & 0xFF);
            if (s.length() == 1) {
                builder.append("0");
            }
            builder.append(s);
        }
        return builder.toString();
    }
}

Register the encoder in a configuration class:

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(); // or return new MyMD5PasswordEncoder();
}

Login Configuration

Three ways to configure login handling:

Form login with request forwarding.

Form login with redirection.

Custom authentication success/failure handlers.

http.formLogin()
    .usernameParameter("name")
    .passwordParameter("pswd")
    .loginPage("/toLogin")
    .loginProcessingUrl("/login")
    .failureForwardUrl("/failure")
    .successForwardUrl("/toMain");

Role and Authority Management

Use methods such as hasAuthority, hasAnyAuthority, hasRole, hasAnyRole, and hasIpAddress to control access based on permissions, roles, or IP addresses.

http.authorizeRequests()
    .antMatchers("/admin/read").hasAuthority("admin")
    .antMatchers("/guest/read").hasAnyRole("管理员", "访客")
    .antMatchers("/ip").hasIpAddress("127.0.0.1")
    .anyRequest().authenticated();

403 Access Denied Handling

Implement AccessDeniedHandler to return a custom HTML response when a user lacks sufficient permissions.

@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(
            "<html><body><div style='width:800px;text-align:center;margin:auto;font-size:24px'>权限不足,请联系管理员</div></body></html>"
        );
        response.getWriter().flush();
    }
}

Remember‑Me Functionality

http.rememberMe()
    .rememberMeParameter("remember-me")
    .tokenValiditySeconds(14*24*60*60)
    .rememberMeCookieName("remember-me")
    .tokenRepository(persistentTokenRepository)
    .userDetailsService(userSecurity);

Method Security Annotations

Enable annotations with @EnableGlobalMethodSecurity and use @Secured, @PreAuthorize, and @PostAuthorize to enforce role or permission checks at the method level.

@Secured({"ROLE_管理员", "ROLE_访客"})
@RequestMapping("/toMain")
public String toMain() { return "main"; }

@PreAuthorize("hasAuthority('admin:write')")
@RequestMapping("/toMain")
public String toMain() { return "main"; }

CSRF Protection

Spring Security includes CSRF protection to prevent cross‑site request forgery attacks. It can be disabled for specific use cases:

http.csrf().disable();

CSRF (Cross‑Site Request Forgery) occurs when an attacker tricks a user's browser into sending unwanted requests to a trusted site, exploiting the fact that browsers automatically include cookies such as the session ID.

Thymeleaf Integration

Add the following dependencies to use Thymeleaf with Spring Security for view‑level access control:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<dependency>
    <groupId>org.thymeleaf.extras</groupId>
    <artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendJavaAuthenticationAuthorizationspring-security
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.