亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Spring Boot 安全性 - 在 Web 服務調用中顯示自定義身份驗證失敗消息

Spring Boot 安全性 - 在 Web 服務調用中顯示自定義身份驗證失敗消息

手掌心 2023-03-31 09:29:25
當用戶嘗試使用暫停、鎖定或無效的帳戶調用我的網絡服務時,我試圖顯示自定義錯誤。問題是,無論我嘗試什么,相同的消息不斷返回:“訪問此資源需要完全身份驗證”我的 CustomUserDetailsService 是這樣的:@Servicepublic class CustomUserDetailsService implements UserDetailsService {    private static final Logger logger = LogManager.getLogger(CustomUserDetailsService.class);    private @Autowired CredentialsServiceQuery credentials;    private @Autowired MemberProfile memberProfile;    @Override    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {        User.UserBuilder builder = null;        try {            boolean exists = credentials.checkUserExists(username);            if (exists) {                memberProfile = credentials.getUserInformation(username);                builder = User.withUsername(username);                builder.password(memberProfile.getPassword());                builder.authorities(getGrantedAuthorities());                logger.info("User exists: {}", username);            } else {                throw new UsernameNotFoundException(SpringSecurityMessageSource.getAccessor().getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", new Object[] {username}, "User credentials is wrong"));            }        } catch (Exception ex) {            throw new UsernameNotFoundException(SpringSecurityMessageSource.getAccessor().getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", new Object[] {username}, "User credentials is wrong"));            //throw new UsernameNotFoundException("An error occured while trying to find the username, " + username, ex);        }        return builder.build();    }    private List<GrantedAuthority> getGrantedAuthorities(){        List<GrantedAuthority> authorities = new ArrayList<>();        authorities.clear();                authorities.add(new SimpleGrantedAuthority("ROLE_USER"));        return authorities;    }}
查看完整描述

1 回答

?
素胚勾勒不出你

TA貢獻1827條經驗 獲得超9個贊

我不得不放棄嘗試讓 Spring Security 自動為入口點提供來自用戶詳細信息服務的異常消息的想法。


因此,我改用自定義身份驗證提供程序以獲得更多控制,并引入了一個名為 ErrorMessage 的自定義服務:


@Getter

@Setter

@ToString

@Service

public class ErrorMessage {

    private String status;

    private String message;

}

@Getter、@Setter 和@ToString 注釋來自 lombok。他們做到了,所以我不必編寫 setter 和 getter 以及 toString 方法。


在我的自定義身份驗證提供程序中,我只是這樣設置錯誤消息:


private @Autowired ErrorMessage errorMessage;    

@Override

        public Authentication authenticate(Authentication authentication) throws AuthenticationException {

            try {

                String username = authentication.getName();

                String password = authentication.getCredentials().toString();


                if (!credentials.checkUserExists(username)) {

                    //set something here

                }


                memberProfile = credentials.getUserInformation(username);


                if (passwordEncoder.matches(password, memberProfile.getPassword())) {

                    logger.info("It matches - encoder!");

                    return new UsernamePasswordAuthenticationToken(username, password, getGrantedAuthorities());

                } else {

                    //error message bean utilised here

                    errorMessage.setStatus("100");

                    errorMessage.setMessage(username + "'s password is incorrect");


                    throw new BadCredentialsException("The credentials provided are incorrect");

                }

            } catch (Exception ex) {

                throw new BadCredentialsException("The credentials provided are incorrect", ex);

            }

        }

然后我以這種方式在入口點獲得自定義錯誤消息:


@Component

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    private @Autowired ErrorMessage errorMessage;


    @Override

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException {

        //String json = String.format("{\"errorcode\": \"%s\", \"message\": \"%s\"}", response.getStatus(), ex.getMessage());

        String json = String.format("{\"errorcode\": \"%s\", \"message\": \"%s\"}", errorMessage.getStatus(), errorMessage.getMessage());

        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        response.setContentType("application/json");

        response.setCharacterEncoding("UTF-8");

        response.getWriter().write(json);

    }

}


查看完整回答
反對 回復 2023-03-31
  • 1 回答
  • 0 關注
  • 139 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號