Activiti7工作流引擎:实战篇 与SpringSecurity集成

Posted vbirdbest

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Activiti7工作流引擎:实战篇 与SpringSecurity集成相关的知识,希望对你有一定的参考价值。

人间正道是沧桑,河南卤面数你香。

1. mapper

public interface UserMapper 
    @Select("select * from tb_user where username=#userName")
    User loadUserByUsername(String userName);

2. service

@Service
public class UserService 

    @Autowired
    private UserMapper userMapper;

    public User loadUserByUsername(String userName)
        return userMapper.loadUserByUsername(userName);
    

注意:在构造SimpleGrantedAuthority时需要对角色前增加前缀 “ROLE_”

@Slf4j
@Component
public class MyUserDetailsService implements UserDetailsService 

    @Autowired
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException 
        User user = userService.loadUserByUsername(username);
        if(user == null)
            return null;
        
        
        List<GrantedAuthority> authority = new ArrayList<>();
        authority.add(new SimpleGrantedAuthority("ROLE_" + user.getRole()));
        return new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                authority);
    

3. handler

@Slf4j
@Component("myAuthSuccessHandler")
public class MyAuthenctiationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler 
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private UserService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException 
        String name = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.loadUserByUsername(name);
        request.getSession().setAttribute("userid", user.getId());
        Result result = new Result(200, "登录成功!!");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(objectMapper.writeValueAsString(result));
    

@Slf4j
@Component("myAuthFailureHandler")
public class MyAuthenctiationFailureHandler extends SimpleUrlAuthenticationFailureHandler 
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException 
        response.setStatus(HttpStatus.FORBIDDEN.value());
        response.setContentType("application/json;charset=UTF-8");
        Result result = new Result(403, "账号或者密码不正确!");
        response.getWriter().write(objectMapper.writeValueAsString(result));
    

4. config

/**
 * SpringSecurity的配置类
 */
@Component
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter 

    @Autowired
    private MyUserDetailsService myUserDetailsService;
    
    @Autowired
    private PasswordEncoder encoder;
    
    @Autowired
    private MyAuthenctiationSuccessHandler myAuthSuccessHandler;
    
    @Autowired
    private MyAuthenctiationFailureHandler myAuthFailureHandler;
    
    /**
     * 用户授权
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception 
        // 使用自定义的认证类实现授权
        auth.userDetailsService(myUserDetailsService).passwordEncoder(encoder);
    

    /**
     * 配置放行的请求
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception 
        web.ignoring().antMatchers("/css/**");
        web.ignoring().antMatchers("/js/**");
        web.ignoring().antMatchers("/img/**");
        web.ignoring().antMatchers("/plugins/**");
        web.ignoring().antMatchers("/login.html");
    

    @Override
    protected void configure(HttpSecurity http) throws Exception 
        //其他任何路径都需要管理员登录
        http.authorizeRequests().
                antMatchers("/**").
                access("hasRole('ADMIN')");

        //登录相关配置
        http.formLogin()
                .loginPage("/login.html")   //指定登录地址
                .loginProcessingUrl("/login")       //指定处理登录的请求地址
                .successHandler(myAuthSuccessHandler) //登录成功的回调
                .failureHandler(myAuthFailureHandler); //登录失败的回调

        //登出配置
        http.logout().
                logoutUrl("/logout").           //登出地址为/logout
                invalidateHttpSession(true);    //并且登出后销毁session

        //设置用户只允许在一处登录,在其他地方登录则挤掉已登录用户,被挤掉的已登录用户则需要返回/login.html重新登录
        http.sessionManagement().maximumSessions(1).expiredUrl("/login.html");

        //关闭CSRF安全策略
        http.csrf().disable();

        //允许跳转显示iframe
        http.headers().frameOptions().disable();

        //异常处理页面,例如没有权限访问等
        http.exceptionHandling().accessDeniedPage("/error.html");
    

    @Bean
    public PasswordEncoder passwordEncoder() 
        return new BCryptPasswordEncoder();
    

5. listener

5.1 ExecutionListener

@Slf4j
@Component
public class MyExecutionListener implements ExecutionListener 

    @Override
    public void notify(DelegateExecution delegateExecution) 
        log.info("delegateExecution is ", delegateExecution);
    

5.2 TaskListener

@Slf4j
@Component
public class MyTaskListener implements TaskListener 

    @Override
    public void notify(DelegateTask delegateTask) 
        
        if(delegateTask.getEventName().equals("assignment"))
            // 消息提醒
        
    

以上是关于Activiti7工作流引擎:实战篇 与SpringSecurity集成的主要内容,如果未能解决你的问题,请参考以下文章

Activiti7工作流引擎:实战篇 与SpringSecurity集成

Activiti7工作流引擎:实战篇 前端演示

Activiti7工作流引擎:实战篇 前端演示

Activiti7工作流引擎:实战篇 准备工作

Activiti7工作流引擎:实战篇 准备工作

Activiti7工作流引擎:进阶篇 Activiti7与Spring整合