Methods to enable Sina Weibo to support SSO authorization:
SSO authorization refers to the authorization method that evokes Weibo client behavior in a simple way with one click, because the operation It is simple, so it is used as a third-party login option for many applications.
Of course, if you want to use this function, you must first have a local client. Otherwise, the web authorization method will be used, and you will slowly enter your account and password to obtain authorization.
Before coding, you have to make some simple preparations for this.
1. Download the official SDK, which contains examples and MD5 signature tools.
Official SDK
The signing tool in it gets the MD5 value based on the package name you enter. You need this value to create the application correctly.
There is also weiboSDK inside, you need to add it to your application and reference its methods.
2. Add network access permissions to the list
3. You need to create an application on Sina's open platform.
Create an app now!
Interface for defining authorization parameters:
(To be honest, I just copied the demo directly and changed it to my own authorization information).
[html] view plaincopyprint?
public interface Constants {
/** The APP_KEY of the current DEMO application, third-party applications should replace this with their own APP_KEY APP_KEY */
public static final String APP_KEY = "1608434710";
public static final String REDIRECT_URL = "";
public static final String SCOPE =< /p>
"email,direct_messages_read,direct_messages_write,"
+ "friendships_groups_read,friendships_groups_write,statuses_to_me_read,"
+ "follow_app_official_microblog," + "invitation_write";
}
Cache authorization information:
[html] view plaincopyprint?
/**
* This class definition Parameters required for Weibo authorization.
*/
public class AccessTokenKeeper {
private static final String PREFERENCES_NAME = "com_weibo_sdk_android";
private static final String KEY_UID = "uid";
private static final String KEY_ACCESS_TOKEN = "access_token";
private static final String KEY_EXPIRES_IN = "expires_in";
/** p>
* Save the Token object to SharedPreferences.
*
* @param context application context environment
* @param token Token object
*/
< p>public static void writeAccessToken(Context context, Oauth2AccessToken token) {if (null == context || null == token) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
Editor editor = pref.edit();
editor.putString( KEY_UID, token.getUid());
editor.putString(KEY_ACCESS_TOKEN, token.getToken());
editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());< /p>
editor.commit();
}
/**
* Read Token information from SharedPreferences.
*
* @param context application context
*
* @return Returns the Token object
*/
public static Oauth2AccessToken readAccessToken(Context context) {
if (null == context) {
return null;
}
Oauth2AccessToken token = new Oauth2AccessToken();
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
token.setUid(pref .getString(KEY_UID, ""));
token.setToken(pref.getString(KEY_ACCESS_TOKEN, ""));
token.setExpiresTime(pref.getLong(KEY_EXPIRES_IN, 0 ));
return token;
}
/**
* Clear the Token information in SharedPreferences.
*
* @param context application context environment
*/
public static void clear(Context context) { p>
if (null == context) {
return;
}
SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND) ;
Editor editor = pref.edit();
editor.clear();
editor.commit();
}
}
Integrated sso authorization + obtaining user name:
[html] view plaincopyprint?
/** p>
* This class mainly demonstrates how to perform authorization and SSO login.
*/
public class WBAuthActivity extends Activity implements OnClickListener {
/** Displays the authenticated information, such as AccessToken */
private TextView mTokenText;
/** Weibo Web authorization class, providing login and other functions*/
private WeiboAuth mWeiboAuth;
/** Encapsulated "access_token", "expires_in", "refresh_token", and provide their management functions */
private Oauth2AccessToken mAccessToken;
/** Note: SsoHandler is only available if the SDK supports SSO Valid when ssoBtn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R .layout.acy_sinasso);
initView();
}
public void initView() {
mTokenText = (TextView) findViewById(R.id.tv_txt);
// SSO authorization
ssoBtn = (Button) findViewById(R.id.btn_sso);
// Create Weibo instance
mWeiboAuth = new WeiboAuth(this, Constants.APP_KEY,
Constants.REDIRECT_URL, Constants.SCOPE);
// From SharedPreferences Read the last saved AccessToken and other information,
// When starting this application for the first time, AccessToken is not available
mAccessToken = AccessTokenKeeper.readAccessToken(this);
if (mAccessToken.isSessionValid()) {
updateTokenView(true);
}
ssoBtn.setOnClickListener(this);
}
/**
* This function is called when the SSO authorization Activity exits.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult( requestCode, resultCode, data);
// SSO authorization callback
// Important: The Activity that initiates SSO login must override onActivityResult
if (mSsoHandler ! = null) {
mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
}
}
/** p>
* Weibo authentication and authorization callback class. 1. During SSO authorization, the callback will not be executed until
* {@link SsoHandler#authorizeCallBack} is called in {@link #onActivityResult}.
2. For non-SSO
* authorization, this callback will be executed when the authorization ends. When the authorization is successful, please save the access_token, expires_in, uid and other information to
* SharedPreferences.
*/
class AuthListener implements WeiboAuthListener {
// Authorization completed
@Override
public void onComplete(Bundle values) {
// Parse Token from Bundle
mAccessToken = Oauth2AccessToken.parseAccessToken(values);
if (mAccessToken.isSessionValid() ) {
// Display Token
updateTokenView(false);
// Save Token to SharedPreferences
AccessTokenKeeper.writeAccessToken(WBAuthActivity .this,
mAccessToken);
Toast.makeText(WBAuthActivity.this, "success!!",
Toast.LENGTH_SHORT).show();
// Get the user's nickname based on uid, because uid is in the data passed from the server by the callback method.
long uid = Long.parseLong(mAccessToken.getUid());
mUsersAPI.show(uid, mListener);
} else {
// You will receive a Code in the following situations:
// 1. When you do not register the package name and signature of the application on the platform;
< p>// 2. When the package name and signature of the application you register are incorrect;// 3. When the package name and signature you register on the platform are different from the package name and signature of the application you are currently testing When the signatures do not match.
Toast.makeText(WBAuthActivity.this, "fail", Toast.LENGTH_LONG)
.show();
}
}
//Cancel authorization
@Override
public void onCancel() {
Toast.makeText(WBAuthActivity.this, " cancel", Toast.LENGTH_LONG)
.show();
}
// Authorization exception
@Override
public void onWeiboException(WeiboException e) {
Toast.makeText(WBAuthActivity.this,
"Auth exception : " + e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
/**
* Display the current Token information .
Whether the token information already exists in the configuration file and is legal
*/
public void updateTokenView(boolean hasExisted) {
// Get user information interface
mUsersAPI = new UsersAPI(mAccessToken);
String date = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
.format(new java .util.Date(mAccessToken.getExpiresTime()));
String format = getString(R.string.weibosdk_demo_token_to_string_format_1);
mTokenText
.setText( String.format(format, mAccessToken.getToken(), date));
String message = String.format(format, mAccessToken.getToken(), date);
if ( hasExisted) {
message = getString(R.string.weibosdk_demo_token_has_existed)
+ "\n" + message;
// Get the user's nickname based on uid , because the uid is in the data passed from the server by the callback method.
long uid = Long.parseLong(mAccessToken.getUid());
mUsersAPI.show(uid, mListener);
}
< p>mTokenText.setText(message);}
/**
* Weibo OpenAPI callback interface.
*/
private RequestListener mListener = new RequestListener() {
@Override
public void onComplete(String response) {< /p>
if (!TextUtils.isEmpty(response)) {
// Call User#parse to parse the JSON string into a User object
User user = User.parse (response);
if (user != null) {
Toast.makeText(WBAuthActivity.this,
"Obtained User information successfully, user nickname: " + user.screen_name,
Toast.LENGTH_LONG).show();
mTokenText.setText(user.screen_name);
} else {
p>Toast.makeText(WBAuthActivity.this, response,
Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onWeiboException(WeiboException e) {
ErrorInfo info = ErrorInfo.parse(e.getMessage());
Toast.makeText(WBAuthActivity.this, info.toString(),
Toast.LENGTH_LONG).show();
}
< p>};@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == ssoBtn) {
mSsoHandler = new SsoHandler(WBAuthActivity.this, mWeiboAuth);
mSsoHandler.authorize(new AuthListener());
}
}
}
Layout:
[html] view plaincopyprint?
android:layout_width="match_parent"< /p> android:layout_height="match_parent" android:orientation="vertical" > android:id="@+id/btn_sso" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" /> android:id="@+id/tv_txt" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="info" />