Spring security登录授权验证的简单例子

x33g5p2x  于2022-02-07 转载在 Spring  
字(6.5k)|赞(0)|评价(0)|浏览(213)

实现一个简单的使用spring security完成的登录验证。登录成功后,自动跳转到index页面。不同的用户,授予不同访问页面路径的权限。权限基于角色管控。admin权限角色最高。user角色为普通角色。

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final String USER = "user";
    private final String ADMIN = "admin";

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .formLogin() //登录
                //.failureUrl("/error") //成功登陆后跳转页面
                .failureHandler(new AuthenticationFailureHandler() {
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest req, HttpServletResponse resp, AuthenticationException exception) {
                        resp.setContentType("application/json;charset=utf-8");
                        PrintWriter out = null;
                        try {
                            out = resp.getWriter();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        out.write("登录失败");
                        out.flush();
                        out.close();
                    }
                })
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        System.out.println(authentication.getName() + " 登录成功");

                        //重定向
                        response.sendRedirect("/index");
                    }
                })
                .permitAll()
                .and();

        //http.rememberMe().tokenValiditySeconds(5);

        http
                .authorizeRequests() // 配置认证与授权
                .antMatchers("/user/**").hasRole(USER) //基于角色
                //.antMatchers("/user/**").hasAuthority("p1") 基于权限
                .antMatchers("/admin/**").hasRole(ADMIN) //基于角色
                //.antMatchers("/admin", "/admin/**").hasAuthority("p2") 基于权限
                //.hasAnyAuthority("admin,manager") 只要有任意一个权限就可访问, 多个权限逗号分隔
                .anyRequest().authenticated()  //需登录才能访问。
                .and();

        //注销登录,退出当前用户
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
//                        resp.setContentType("application/json;charset=utf-8");
//                        PrintWriter out = resp.getWriter();
//                        out.write("退出登录");
//                        out.flush();
//                        out.close();

                        resp.sendRedirect("/login");
                    }
                })
                .logoutSuccessUrl("/login")
                .permitAll()
                .and();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("admin")
                //.authorities("p1", "p2") 基于权限
                .password("admin").roles(USER, ADMIN) //基于角色
                .and()
                .withUser("fly")
                //.authorities("p1") 基于权限
                .password("123456").roles(USER) //基于角色
                .and()
                .passwordEncoder(new MyPasswordEncoder());
    }
}

权限为user的角色,只能访问user下的页面。admin角色可以访问所有页面。在代码中创建了两个账户,admin和fly,admin为“admin”角色,fly为“user”角色。

spring security默认自带有一个login的页面。除非代码中指定,否则,formLogin()默认启用就是spring security自带的login页面。

上面的代码中用到了MyPasswordEncoder,自定义实现的:

import org.springframework.security.crypto.password.PasswordEncoder;

public class MyPasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        return rawPassword.toString();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return rawPassword.equals(encodedPassword);
    }
}

接下来写一个页面的controller控制器:

import org.springframework.security.access.annotation.Secured;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@Controller
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class MyWebPageController {
    @GetMapping("/user/{username}")
    @ResponseBody //表示当前函数完成对于当前路由请求的处理后,并把返回的结果直接给浏览器。
    public String getUser(@PathVariable String username) {
        return username;
    }

    @GetMapping("")
    public void redirectToindex(HttpServletResponse response) {
        try {
            //重定向
            response.sendRedirect("/login");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/index")
    @ResponseBody
    public String index() {
        String info_name = "未登录用户";
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            info_name = authentication.getName();
        }

        return info_name + "@index@" + System.currentTimeMillis();
    }

    @GetMapping("/admin")
    @ResponseBody
    public String adminPage(Authentication authentication) {
        return authentication.getName() + "@" + System.currentTimeMillis();
    }

    @GetMapping("/user")
    @ResponseBody
    public String userPage(Authentication authentication) {
        return "user " + authentication.getName() + "@" + System.currentTimeMillis();
    }

    @GetMapping("/whoami")
    @ResponseBody
    public String whoami(Authentication authentication) {
        //返回当前登录用户是谁?
        return "I am " + authentication.getName() + "@" + System.currentTimeMillis();
    }

    @GetMapping("/super")
    @Secured({"ROLE_admin"})
    @ResponseBody
    public String superUser(Authentication authentication) {
        //返回当前登录用户是谁?
        return "super " + authentication.getName() + "@" + System.currentTimeMillis();
    }
}

作为示例目的,@Secured({"ROLE_admin"}) 只允许admin角色访问,按照规范,需要在注解@Secured({"ROLE_xxxxx"})。

application很简单:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringSecurityApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringSecurityApplication.class, args);
    }
}

相关文章

微信公众号

最新文章

更多