Custom Authentication Provider in Spring

The Spring Security module supports by default some standard ways to retrieve user information for authentication from databases, LDAP or other commonly used storages. But unfortunately the Spring documentation does not say much about creating connections to custom data sources. There are actually several different ways to do it.

But let’s say we have a Spring MVC application with a login form which contains a user name and password field, but the application does not use any of the supported methods to store the user data. How can we authenticate the user anyway?

The easiest way in my opinion is to create a new authentication provider. So we simply need to implement the AuthenticationProvider interface.

The authenticate() function of the class must return an UsernamePasswordAuthenticationToken instance if the authentication is successful or null otherwise. You can choose another token, simple check the classes implementing AbstractAuthenticationToken. But for our scenario this should be enough.

It is important to populate the list of authorities we grant the user. I used the standard user role (“ROLE_USER”).

In the real-world you might want to add a member variable to the authentication provider pointing to a bean which contains the code for authenticating an user, here I just hard-coded it (name must be “admin”, password “system”).

@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();
        if (name.equals("admin") && password.equals("system")) {
            List<GrantedAuthority> grantedAuths = new ArrayList<>();
            grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER"));
            Authentication auth = new UsernamePasswordAuthenticationToken(name, password, grantedAuths);
            return auth;
        } else {
            return null;
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}

Now we need to declare the new authentication provider in our configuration:

<authentication-manager>
    <authentication-provider ref="customAuthenticationProvider"/>
</authentication-manager>

And that’s it!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值