1 package org.springframework.security.oauth2.provider.code;
2
3 import java.sql.ResultSet;
4 import java.sql.SQLException;
5 import java.sql.Types;
6
7 import javax.sql.DataSource;
8
9 import org.springframework.dao.EmptyResultDataAccessException;
10 import org.springframework.jdbc.core.JdbcTemplate;
11 import org.springframework.jdbc.core.RowMapper;
12 import org.springframework.jdbc.core.support.SqlLobValue;
13 import org.springframework.security.oauth2.common.util.SerializationUtils;
14 import org.springframework.security.oauth2.provider.OAuth2Authentication;
15 import org.springframework.util.Assert;
16
17
18
19
20
21
22
23 public class JdbcAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {
24
25 private static final String DEFAULT_SELECT_STATEMENT = "select code, authentication from oauth_code where code = ?";
26 private static final String DEFAULT_INSERT_STATEMENT = "insert into oauth_code (code, authentication) values (?, ?)";
27 private static final String DEFAULT_DELETE_STATEMENT = "delete from oauth_code where code = ?";
28
29 private String selectAuthenticationSql = DEFAULT_SELECT_STATEMENT;
30 private String insertAuthenticationSql = DEFAULT_INSERT_STATEMENT;
31 private String deleteAuthenticationSql = DEFAULT_DELETE_STATEMENT;
32
33 private final JdbcTemplate jdbcTemplate;
34
35 public JdbcAuthorizationCodeServices(DataSource dataSource) {
36 Assert.notNull(dataSource, "DataSource required");
37 this.jdbcTemplate = new JdbcTemplate(dataSource);
38 }
39
40 @Override
41 protected void store(String code, OAuth2Authentication authentication) {
42 jdbcTemplate.update(insertAuthenticationSql,
43 new Object[] { code, new SqlLobValue(SerializationUtils.serialize(authentication)) }, new int[] {
44 Types.VARCHAR, Types.BLOB });
45 }
46
47 public OAuth2Authentication remove(String code) {
48 OAuth2Authentication authentication;
49
50 try {
51 authentication = jdbcTemplate.queryForObject(selectAuthenticationSql,
52 new RowMapper<OAuth2Authentication>() {
53 public OAuth2Authentication mapRow(ResultSet rs, int rowNum)
54 throws SQLException {
55 return SerializationUtils.deserialize(rs.getBytes("authentication"));
56 }
57 }, code);
58 } catch (EmptyResultDataAccessException e) {
59 return null;
60 }
61
62 if (authentication != null) {
63 jdbcTemplate.update(deleteAuthenticationSql, code);
64 }
65
66 return authentication;
67 }
68
69 public void setSelectAuthenticationSql(String selectAuthenticationSql) {
70 this.selectAuthenticationSql = selectAuthenticationSql;
71 }
72
73 public void setInsertAuthenticationSql(String insertAuthenticationSql) {
74 this.insertAuthenticationSql = insertAuthenticationSql;
75 }
76
77 public void setDeleteAuthenticationSql(String deleteAuthenticationSql) {
78 this.deleteAuthenticationSql = deleteAuthenticationSql;
79 }
80 }