AdSense

網頁

2019/10/2

Spring Security 在UserDetailsService取得request物件
Get request in UserDetailsService

在Spring Security自訂的UserDetailsService中取得HttpServletRequest物件的方法如下。


把自訂的UserDetailsService註冊為bean,並直接用@Autowired注入HttpServletRequest

例如下面是自訂的DemoUserDetailsService,類別名稱上掛有@Service並由Spring Boot掃描並自動註冊為bean,所以可直接透過@Autowired注入HttpServletRequest的實例。

DemoUserDetailsService

package com.abc.demo.config;

import javax.servlet.http.HttpServletRequest;

import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class DemoUserDetailsService implements UserDetailsService {

    @Autowired
    private HttpServletRequest request; // inject

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        
        ...

    }

}

參考:

沒有留言:

AdSense