13.12 Spring Boot集成Security中遇到的问题13.12 Spring Boot集成Security中遇到的问题问题1:Spring Boot集成Security使用数据库用户角色

13.12 Spring Boot集成Security中遇到的问题

问题1:Spring Boot集成Security使用数据库用户角色权限用户名问题

问题描述

代码

package com.springboot.in.action.dao

import java.util.List

import com.springboot.in.action.entity.User
import org.springframework.data.jpa.repository.Query
import org.springframework.data.repository.CrudRepository

import scala.language.implicitConversions

trait UserDao extends CrudRepository[User, Integer] {
  def findAll(): List[User] // JavaConversions

  def save(u: User): User

  def findOne(id: Integer): User

  @Query(value = "select * from `user` where `username` = 1? limit 1", nativeQuery = true)
  def findByUsername(username: String): User


}

报错日志

Caused by: org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:261)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy97.findByUsername(Unknown Source)
    at com.springboot.in.action.service.LightSwordUserDetailService.loadUserByUsername(LightSwordUserDetailService.scala:25)
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
    ... 54 common frames omitted
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
    at org.hibernate.loader.Loader.getResultSet(Loader.java:2117)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1900)
    at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1876)
    at org.hibernate.loader.Loader.doQuery(Loader.java:919)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
    at org.hibernate.loader.Loader.doList(Loader.java:2617)
    at org.hibernate.loader.Loader.doList(Loader.java:2600)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429)
    at org.hibernate.loader.Loader.list(Loader.java:2424)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:336)
    at org.hibernate.internal.SessionImpl.listCustomQuery(SessionImpl.java:1967)
    at org.hibernate.internal.AbstractSessionImpl.list(AbstractSessionImpl.java:322)
    at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:125)
    at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
    at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:529)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)

.....

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''jack'' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425)
    at com.mysql.jdbc.Util.getInstance(Util.java:408)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:943)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2501)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1966)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.apache.tomcat.jdbc.pool.StatementFacade$StatementProxy.invoke(StatementFacade.java:138)
    at com.sun.proxy.$Proxy100.executeQuery(Unknown Source)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
    ... 98 common frames omitted

原因分析

sql语法手误。1?这地方写错了,应该是?1。这在敲代码的时候,手速一旦稍有不慎,就会导致前后顺序颠倒,而导致输入错误。这个虽然说是“低级错误”,但是错误搞起来,确实有时候很难想到这个你从来不会认为出错的地方。

@Query(value = "select * from `user` where `username` = 1? limit 1", nativeQuery = true)
  def findByUsername(username: String): User

解决方案

@Query(value = "select * from `user` where `username` = ?1 limit 1", nativeQuery = true)
  def findByUsername(username: String): User

问题2:Spring Boot集成Security使用数据库用户角色权限ROLE_问题

问题描述

日志打出来的ROLE是USER,代码里调用的是@PreAuthorize("hasRole('USER')"),为什么权限却是不对?

后台打印日志:

username is jack, USER LoginFilter:{ "accountNonExpired":true, "accountNonLocked":true, "authorities":[{ "authority":"USER" }], "credentialsNonExpired":true, "enabled":true, "username":"jack" }

调用代码:

@RestController
@RequestMapping(Array("/httpapi"))
class HttpApiController @Autowired()(
                                      val HttpSuiteDao: HttpSuiteDao,
                                      val HttpApiDao: HttpApiDao,
                                      val HttpReportDao: HttpReportDao) {

  @PreAuthorize("hasRole('USER')")
  @RequestMapping(value = {
    Array("", "/")
  }, method = Array(RequestMethod.GET))
  def list(model: Model) = {
    model.addAttribute("httpapis", HttpApiDao.findAll())
    new ModelAndView("/httpapi/list")
  }

....


}

数据库存的是USER:

package com.springboot.in.action.service

import javax.annotation.PostConstruct

import com.springboot.in.action.dao.{RoleDao, UserDao, UserRoleDao}
import com.springboot.in.action.entity.{Role, User, UserRole}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

/**
  * Created by jack on 2017/4/29.
  * 初始化测试数据
  */
//@Service // 需要初始化数据时,打开注释即可。
class DataInit @Autowired()(val userDao: UserDao,
                            val userRoleDao: UserRoleDao,
                            val roleDao: RoleDao) {

  @PostConstruct def dataInit(): Unit = {
    val admin = new User
    val jack = new User

    admin.username = "admin"
    admin.password = "admin"

    jack.username = "jack"
    jack.password = "123456"

    userDao.save(admin)
    userDao.save(jack)

    val adminRole = new Role
    val userRole = new Role

    adminRole.role = "ADMIN"
    userRole.role = "USER"

    roleDao.save(adminRole)
    roleDao.save(userRole)

    val userRoleAdminRecord1 = new UserRole
    userRoleAdminRecord1.userId = admin.id
    userRoleAdminRecord1.roleId = adminRole.id
    userRoleDao.save(userRoleAdminRecord1)

    val userRoleAdminRecord2 = new UserRole
    userRoleAdminRecord2.userId = admin.id
    userRoleAdminRecord2.roleId = userRole.id
    userRoleDao.save(userRoleAdminRecord2)

    val userRoleJackRecord = new UserRole
    userRoleJackRecord.userId = jack.id
    userRoleJackRecord.roleId = userRole.id
    userRoleDao.save(userRoleJackRecord)


  }

}

原因分析:

Spring Security默认前缀ROLE_问题。这个应该是框架的一个小缺陷。总感觉这样的一个潜规则在这里有点不大优雅。

解决方案

数据库里面存的role角色要加上默认前缀:ROLE_

    adminRole.role = "ROLE_ADMIN"
    userRole.role = "ROLE_USER"

这样改完之后,代码调用的地方保持不变,数据库里面角色必须统一有ROLE_前缀。而我们看到的后台打印的日志内容也是数据库的信息:

username is jack, ROLE_USER
LoginFilter:{
    "accountNonExpired":true,
    "accountNonLocked":true,
    "authorities":[{
        "authority":"ROLE_USER"
    }],
    "credentialsNonExpired":true,
    "enabled":true,
    "username":"jack"
}

这个小坑,估计很多初次学习使用Security框架的人都会踩到。所以,记个问题,以供参考。

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏蛋未明的专栏

Build a JavaScript Compressor tool using NodeJS, ExpressJS, Jade, UglifyJS tutorial Read more: http

1192
来自专栏along的开发之旅

Mac os 下打开java内存分析工具 mat

版权声明:欢迎传播,请标明出处。 https://blog.csdn.net/u201011221/article/details/8305...

5823
来自专栏岑玉海

sqoop 从sqlserver2008 导入数据到hadoop

  今天终于开始上手导入数据到hadoop了,哈哈,过程蛮崎岖的,和官方文档的还不太一样。   OK,let's go!试验对象是我第一个名为ST_Statis...

4075
来自专栏Ryan Miao

MongoDB - basic

mongoDB basic from:http://www.tutorialspoint.com/mongodb prject:https://github....

3246
来自专栏Hongten

Cannot create PoolableConnectionFactory (Communications link failure)--Connection refused: connect

 我知道是连接数据库的时候出现了错误,我检查了我的tomcat的配置文件context.xml文件

2461
来自专栏小筱月

SSM 使用 mybatis 分页插件 pagehepler 实现分页

前几天在这里分享了手写 sql 分页查询实现分页,现在来看看使用 mybatis 分页插件 pagehepler 来实现分页

3021
来自专栏码匠的流水账

聊聊eureka的delta配置

eureka-client-1.8.8-sources.jar!/com/netflix/discovery/DiscoveryClient.java

901
来自专栏小巫技术博客

Retrofit2 & RxJava2实现单文件和多文件上传

5224
来自专栏颇忒脱的技术博客

Servlet 3.1 Async IO分析

Servlet Async Processing提供了一种异步请求处理的手段(见我的另一篇文章Servlet 3.0 异步处理详解),能够让你将Http thr...

1443
来自专栏冷冷

Spring Security Oauth2 自定义短信验证码登录

spring security oauth2 登录过程详解 未命名文件.png 定义手机号登录令牌 /** * @author lengleng * @...

6197

扫码关注云+社区

领取腾讯云代金券